七、线程间通讯
一般而言,应用程序中的一个次要线程总是为主线程执行特定的任务,这样,主线程和次要线程间必定有一个信息传递的渠道,也就是主线程和次要线程间要进行通信。这种线程间的通信不但是难以避免的,而且在多线程编程中也是复杂和频繁的,下面将进行说明。
例程7 MultiThread7
该例程演示了如何使用自定义消息进行线程间通信。首先,主线程向CCalculateThread线程发送消息
WM_CALCULATE,CCalculateThread线程收到消息后进行计算,再向主线程发送WM_DISPLAY消息,主线程收到该消息后显示
计算结果。
protected:
int nAddend;
void CMultiThread7Dlg::OnRadio1()
{
nAddend=10;
}
void CMultiThread7Dlg::OnRadio2()
{
nAddend=50;
}
void CMultiThread7Dlg::OnRadio3()
{
nAddend=100;
}
BOOL CMultiThread7Dlg::OnInitDialog()
{
……
((CButton*)GetDlgItem(IDC_RADIO1))->SetCheck(TRUE);
nAddend=10;
……
#include "CalculateThread.h"
#define WM_DISPLAY WM_USER+2
class CMultiThread7Dlg : public CDialog
{
// Construction
public:
CMultiThread7Dlg(CWnd* pParent = NULL); // standard constructor
CCalculateThread* m_pCalculateThread;
……
protected:
int nAddend;
LRESULT OnDisplay(WPARAM wParam,LPARAM lParam);
……
BEGIN_MESSAGE_MAP(CMultiThread7Dlg, CDialog)
……
ON_MESSAGE(WM_DISPLAY,OnDisplay)
END_MESSAGE_MAP()
LRESULT CMultiThread7Dlg::OnDisplay(WPARAM wParam,LPARAM lParam)
{
int nTemp=(int)wParam;
SetDlgItemInt(IDC_STATUS,nTemp,FALSE);
return 0;
}
void CMultiThread7Dlg::OnSum()
{
m_pCalculateThread=
(CCalculateThread*)AfxBeginThread(RUNTIME_CLASS(CCalculateThread));
Sleep(500);
m_pCalculateThread->PostThreadMessage(WM_CALCULATE,nAddend,NULL);
}
#define WM_CALCULATE WM_USER+1
class CCalculateThread : public CWinThread
{
……
protected:
afx_msg LONG OnCalculate(UINT wParam,LONG lParam);
……
LONG CCalculateThread::OnCalculate(UINT wParam,LONG lParam)
{
int nTmpt=0;
for(int i=0;i<=(int)wParam;i++)
{
nTmpt=nTmpt+i;
}
Sleep(500);
::PostMessage((HWND)(GetMainWnd()->GetSafeHwnd()),WM_DISPLAY,nTmpt,NULL);
return 0;
}
BEGIN_MESSAGE_MAP(CCalculateThread, CWinThread)
//{{AFX_MSG_MAP(CCalculateThread)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
ON_THREAD_MESSAGE(WM_CALCULATE,OnCalculate)
//和主线程对比,注意它们的区别
END_MESSAGE_MAP()
#include "MultiThread7Dlg.h"以上代码为 CCalculateThread 类添加了 WM_CALCULATE 消息,消息的响应函数是
文章评论(0条评论)
登录后参与讨论