C++ thread synchronization example analysis
- 2020-04-02 02:48:03
- OfStack
This paper analyzes the C++ thread synchronization problem, to share for your reference. Specific analysis is as follows:
This instance sets the global variable g_bContinue, sets the global variable g_bContinue in the main thread, and the worker thread detects the global variable to realize the purpose of the main thread controlling the worker thread.
The printed values of g_cnt1 and g_cnt2 are different because of the time slice switching during thread debugging.
The specific code is as follows:
//CountError. CPP: defines the entry point for the console application.
//
#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=%dn",g_cnt1);
printf("g_cnt2=%dn",g_cnt2);
::CloseHandle(hThread[0]);
::CloseHandle(hThread[1]);
return 0;
}
Hope that the article described in the C++ programming to help you.