线程间通信

----------------------------------------------------------------------------------------
①、最常用的方式:全局变量或者多个线程都能看到的一个东东
1、全局变量方式;

int g_Num = 100;
UINT __cdecl ThreadWriteProc(LPVOID lpParameter)
{
	while(TRUE) {
		++g_Num;
		Sleep(50);
	}
	return 100;
}

UINT __cdecl ThreadReadProc(LPVOID lpParameter)
{
	CString strTipMsg;
	while(TRUE) {
		strTipMsg.Format(_T("%d"), g_Num);
		OutputDebugString(strTipMsg);
		Sleep(50);
	}

	return 100;
}

void CThreadTestDlg::OnBnClickedBtn()
{
	CWinThread *pThread = AfxBeginThread(ThreadWriteProc, NULL);
	AfxBeginThread(ThreadReadProc, NULL);
}


2、大家都能访问到的一个东东;

3、全局变量的声明方式;
===================================================
②、发消息方式:PostThreadMessage
#define MY_THREAD_MSG (WM_USER+100)
UINT __cdecl ThreadWriteProc(LPVOID lpParameter)
{
	int nCount = 0;
	DWORD dwThreadReadID = (DWORD)lpParameter;
	while(TRUE) {
		PostThreadMessage(dwThreadReadID, MY_THREAD_MSG, nCount++, NULL);
		Sleep(50);
	}
	return 0;
}

UINT __cdecl ThreadPrintProc(LPVOID lpParameter)
{
	MSG msg = {0};
	while(GetMessage(&msg, 0, 0, 0))
	{
		switch(msg.message) {
			case MY_THREAD_MSG:
				{
					int nCount = (int)msg.wParam;
					CString strText;
					strText.Format(_T("%d"), nCount);
					OutputDebugString(strText);
				}
				break;
		}
	}

	return 0;
}

void CThreadTestDlg::OnBnClickedBtn()
{
	CWinThread *pThreadPrint = AfxBeginThread(ThreadPrintProc, NULL);
	CWinThread *pThreadWrite = AfxBeginThread(ThreadWriteProc, (LPVOID)pThreadPrint->m_nThreadID);
}


===================================================
③、与界面线程方面的联系!
1、创建界面线程的返回值 CWinThread 类型指针,就是新线程的指针;
2、在新界面线程中调用 AfxGetApp(); 获取到的是程序主线程的指针;


通过以上两种方法中的任意一种,将指针进行强制类型转换之后,可以轻松的实现线程间的通信!


3、对于 PostThreadMessage 方式的通信,界面线程同样适用,重载界面线程类的 PreTranslateMessage 即可!
===================================================
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值