C++线程同步源码
设置全局变量g_bContinue,在主线程中设置全局变量g_bContinue,工作线程检测该全局变量,实现主线程控制工作线程的目的……
打印出的g_cnt1与g_cnt2的数值不同,是因为线程调试时时间片的切换……
#include "stdafx.h"
#include <Windows.h>
DWORD g_cnt1;
DWORD g_cnt2;
BOOL g_bContinue = TRUE;
DWORD WINAPI ThreadProc(__inLPVOID lpParameter)
{
while(g_bContinue)
{
g_cnt1++;
g_cnt2++;
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread;
g_cnt1 = g_cnt2 = 0;
hThread = ::CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
hThread = ::CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
Sleep(1000);
g_bContinue = FALSE;
::WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
printf("g_cnt1=%d\n",g_cnt1);
printf("g_cnt2=%d\n",g_cnt2);
::CloseHandle(hThread);
::CloseHandle(hThread);
return 0;
}
页:
[1]