function function: Initialize
Function Prototypes:
void InitializeCriticalSection (lpcritical_sectionlpcriticalsection);
Function Description: The key segment variable must be initialized before it is defined.
function function: Destroy
Function Prototypes:
void DeleteCriticalSection (lpcritical_sectionlpcriticalsection);
Function Description: After use, remember to destroy.
function function: Enter key area
Function Prototypes:
void EnterCriticalSection (lpcritical_sectionlpcriticalsection);
Function Description: The system ensures that each thread is mutually exclusive into the critical area.
function function: Off-switch key area
Function Prototypes:
void LeaveCriticalSection (lpcritical_sectionlpcriticalsection);
The output sets the tickets as a critical resource and is accessed by two processes in turn
#include <stdio.h> #include <process.h> #include <windows.h> int tickets=50; critical_section g_cs;unsigned int __stdcall Fun1 (VOID *lp) {while (true) {Sleep (1);//This is going to be outside of the critical section, otherwise the resource switch thread causes Waste entercriticalsection (&g_cs), if (tickets>0) {printf ("Thread1%d\n", tickets--); LeaveCriticalSection (&g_cs);} Else{leavecriticalsection (&g_cs); break;}} return 0;} unsigned int __stdcall Fun2 (VOID *lp) {while (true) {Sleep (1); EnterCriticalSection (&g_cs); if (tickets>0) {printf ("Thread2%d\n", tickets--); LeaveCriticalSection (&g_cs);} Else{leavecriticalsection (&g_cs); break;}} return 0;} int main () {initializecriticalsection (&G_CS);//initialization to be in front of the definition handle, otherwise the thread may be called the critical section is not initialized handle handle1,handle2; handle1= (HANDLE) _beginthreadex (null,0,fun1,null,0,null); handle2= (HANDLE) _beginthreadex (null,0,fun2,null,0,null ); CloseHandle (HANDLE1); CloseHandle (Handle2); Sleep (4000);D eletecriticalsection (&g_cs); return 0;}
Multithreading-critical section