1. Critical section Object
A critical section is a method that guarantees that only one thread can access the data at a certain time. In the process of using it, it is necessary to provide each thread with a shared critical section object, which can access the protected data regardless of which thread occupies the critical section object, while the other thread waits until the critical section object is released by the thread, and the other thread can take over the critical section. To access the shared data.
2, the main function method
InitializeCriticalSection (&CS);//Initialize critical section entercriticalsection (&CS);//Enter critical section leavecriticalsection (&CS) ;//Leave critical section deletecriticalsection (&CS);//Delete critical section
3. code example
Global variable declaration:
int g_count1 = 0;int G_count2 = 0; BOOL g_bcontinue = FALSE; Critical_section G_cs;
Thread handler functions:
UINT _stdcall ThreadFunc (LPVOID)//thread handling function {:: EnterCriticalSection (&g_cs);//Enter while (g_bcontinue) {G_count1++;g_ Count2++;}::leavecriticalsection (&g_cs);//Leave return 0;}
Call Function:
void Cmultithreadsyncdlg::onbnclickedbutton1 () {//TODO: Add control notification Handler code here G_COUNT1 = G_count2 = 0;::i Nitializecriticalsection (&g_cs);//Initialize//g_sync_flag = Flag_critical;g_bcontinue = TRUE; UINT uId; HANDLE h[2];h[0] = (HANDLE):: _beginthreadex (NULL, 0, threadfunc, NULL, 0, &UID); h[1] = (HANDLE):: _beginthreadex (null , 0, ThreadFunc, NULL, 0, &uid);//wait for sleep (+), g_bcontinue = False;::waitformultipleobjects (2, H, TRUE, INFINITE);: : CloseHandle (H[0]);:: CloseHandle (H[1]);::D eletecriticalsection (&G_CS);//delete//cstring str;//str. Format (_t ("g_count1 =%d\r\ng_count2 =%d\r\n"), G_count1, G_count2);//m_fact. SetWindowText (str);}
Thread synchronization-critical Section objects