C++/MFC线程间通信

1.通过全局变量方式

mfcDlg.cpp

 1 int g_num; //全局变量
 2 UINT _cdecl ThreadWrite(LPVOID lpParameter)
 3 {
 4     g_num = 100;
 5     while (1)
 6     {        
 7         g_num++;
 8         Sleep(50);
 9     }
10     return 0;
11 }
12 UINT _cdecl ThreadRead(LPVOID lpParameter)
13 {
14     CString str;
15     while (true)
16     {
17         str.Format(_T("%d"),g_num);
18         AfxMessageBox(str);
19     }
20     return 0;
21 }
22 
23 void CmfcThreadDlg::OnBnClickedOk()
24 {
25     AfxBeginThread(ThreadWrite, NULL);
26     AfxBeginThread(ThreadRead, NULL);
27 }

如果要在1.cpp中使用g_num,需要在mfcDlg.cpp的头文件中声明extern int g_num。1.cpp中要包含mfcDlg.h

2.通过主对话框类的成员变量,在创建线程时传递主对话框类的指针;

3.界面线程间通信。

界面线程创建时,无法传递参数。

主线程在创建界面线程时,有返回值CWinThread*,即是子线程的指针,使用时类型转换即可。

1 void CmfcThreadDlg::OnBnClickedthread()
2 {
3     // TODO: 在此添加控件通知处理程序代码
4     //创建界面线程
5     CWinThread* pthread= AfxBeginThread(RUNTIME_CLASS(CUIThreadApp));
6     ((CUIThreadApp*)pthread)->child_num = 100; //child_num为子线程的成员变量
7 }

子线程被创建后可以通过AfxGetApp来得到项目主线程的指针。

1 void CTestDlg::OnBnClickedCancel()
2 {
3     // TODO: 在此添加控件通知处理程序代码
4     CWinApp* pApp = AfxGetApp();
5     ((CmfcThreadApp*)pApp)->parent_num=1000;  //项目主线程为cmfcThreadApp
6 }