- 注册时间
- 2011-3-6
- 最后登录
- 1970-1-1
该用户从未签到
|
设置全局变量g_bContinue,在主线程中设置全局变量g_bContinue,工作线程检测该全局变量,实现主线程控制工作线程的目的……
打印出的g_cnt1与g_cnt2的数值不同,是因为线程调试时时间片的切换……
// countError.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <Windows.h>
DWORD g_cnt1;
DWORD g_cnt2;
BOOL g_bContinue = TRUE;
DWORD WINAPI ThreadProc(__in LPVOID lpParameter)
{
while(g_bContinue)
{
g_cnt1++;
g_cnt2++;
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread[2];
g_cnt1 = g_cnt2 = 0;
hThread[0] = ::CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
hThread[1] = ::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[0]);
::CloseHandle(hThread[1]);
return 0;
} |
|