A critical section is a way to implement thread synchronization. Windows provides 4 functions for the critical section (Initializecriticalsection,entercriticalsection,leavecriticalsection, DeleteCriticalSection), to use these functions, you must first have a critical section variable,
Critical_section CS;
The critical section variable, cannot be copied, cannot be moved, and cannot read the field inside (the address of the critical section variable can be taken). In a word, when we write a program, we must treat the critical section variable as a black box , and all the operations on the critical section must go through the 4 functions.
Before you use a critical section, you must initialize it with the InitializeCriticalSection function:
InitializeCriticalSection (&CS);
A thread can enter a critical section through the EnterCriticalSection function:
EnterCriticalSection (&CS);
Once a thread enters a critical section, other threads cannot enter the critical section.
A thread can leave a critical section through the LeaveCriticalSection function:
LeaveCriticalSection (&CS);
When a thread leaves a critical section, other threads can enter the critical section.
When the critical section is no longer needed by the program, do not forget to destroy it.
DeleteCriticalSection (&CS);
Usage and examples:
The usage of a critical section is that if a variable (recorded as x) needs to be shared by multiple threads, then a critical section can be engaged. Before accessing x, any thread must first enter the critical section, complete the access to X, and leave the critical section. Because a critical section allows only one thread to enter at a time, it ensures that x can be accessed by only one thread at a time.
In the following example, n is a variable protected by a critical section.
#include <iostream> #include <windows.h>critical_section cs;int n = 0;dword Thread1 (void *) {//other code Ente Rcriticalsection (&CS); ++n; LeaveCriticalSection (&CS); Other code}dword Thread2 (void *) {//other code entercriticalsection (&CS); n = 5; LeaveCriticalSection (&CS); Other code}void main () {initializecriticalsection (&CS); Sleep (5000); DeleteCriticalSection (&CS);}
Windows thread Synchronization "2" critical section