This article describes the C + + using CriticalSection method to implement thread synchronization, in the previous C + + thread synchronization case analysis based on the addition of four lines of code, the use of four functions:
EnterCriticalSection::D eletecriticalsection:: entercriticalsection:: LeaveCriticalSection At this time, the number printed out is equal.
The specific code is as follows:
#include "stdafx.h"
#include <Windows.h>
DWORD g_cnt1;
DWORD G_cnt2;
BOOL g_bcontinue = TRUE;
Critical_section CS;
DWORD WINAPI ThreadProc (__in lpvoid lpparameter)
{
:: EnterCriticalSection (&CS);
while (g_bcontinue)
{
g_cnt1++;
g_cnt2++
}
:: LeaveCriticalSection (&CS);
return 0;
}
int _tmain (int argc, _tchar* argv[])
{
HANDLE hthread[2];
g_cnt1 = G_cnt2 = 0;
:: InitializeCriticalSection (&CS);
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);
::D eletecriticalsection (&CS);:
: CloseHandle (Hthread[0]);::
CloseHandle (hthread[1]);
return 0;
}
I hope this article will help you with the C + + program design.