- 注册时间
- 2021-4-16
- 最后登录
- 2024-7-10
- 在线时间
- 5 小时
编程入门
- 龙马币
- 93
|
设置全局变量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(__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;
- }
复制代码
|
|