①、最常用的方式:全局变量或者多个线程都能看到的一个东东
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);//
CWinThread::m_nThreadID |
当前线程的ID。 |
}
===================================================