This article analyzes the C + + thread synchronization problem and share it for everyone's reference. The specific analysis is as follows:
This instance sets the global variable g_bcontinue, sets the global variable g_bcontinue in the main thread, detects the global variable by the worker thread, and realizes the purpose of the main thread controlling the worker threads.
The printed g_cnt1 are different from the G_cnt2 values because the time slice switches when the thread is debugged.
The specific code is as follows:
CountError.cpp: Defines the entry point for a 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=%d\n", g_cnt1);
printf ("g_cnt2=%d\n", G_cnt2);::
CloseHandle (hthread[0);
:: CloseHandle (hthread[1))
; return 0;
}
I hope this article will help you with the C + + program design.