The critical section is also called the critical code segment. Shared variables are used to read and write securely when sharing variables in multiple threads. The code is as follows:
Critical_section??? G_cssync?=? {};//critical section int??? G_idata?=?0;dword?? WINAPI?? Writethreadproc (Lpvoid?lpparameter) {//write thread while? 1) {Sleep (+); __try{entercriticalsection (&g_cssync); g_idata++;} __finally{leavecriticalsection (&g_cssync);}} return?0;} DWORD? WINAPI?? Readthreadproc (Lpvoid?lpparameter) {//Read thread while? true) {Sleep (+); __try{entercriticalsection (&g_cssync);//Enter critical section char?str[20]?=?{}; Itoa (G_IDATA,?STR,?10); TRACE (str);} __finally{leavecriticalsection (&g_cssync);//Leave the critical area}}return?0;} void? Ctestthreaddlg::onbnclickedbutton16 () {initializecriticalsectionandspincount (&g_cssync,?0x4000);// Initialize critical section DWORD?? threadid?=?0; HANDLE?? Hthread[2]?=? {};hthread[0]?=? CreateThread (null,?0,? ( Lpthread_start_routine) Writethreadproc,?????????????????????? Null? Create_suspended,?&threadid); hthread[1]?=? CreateThread (null,?0,? ( Lpthread_start_routine) Readthreadproc,?????????????????????? Null? Create_suspended,?&threadid); ResumeThread (Hthread[0]); ResumeThread (hthread[1]); WaitForMultipleObjects (2,?hthread,? TRUE,? INFINITE); CloseHandle (Hthread[0]); CloseHandle (hthread[1]);D eletecriticalsection (&g_cssync);//delete critical section}
Critical sections in multi-threading