Simply put, when a thread executes the entercritialsection, the information inside the CS is modified to indicate which thread is consuming it. At this point, no resources are "locked". No matter what resources, other threads can still be accessed (of course, the result of execution may be wrong). However, before the thread has executed leavecriticalsection, the other thread encounters the Entercritialsection statement, and the thread is in a wait state, which is equivalent to being suspended. In this case, it is the role of protecting shared resources.
It is also because critical_section is so useful that the statements that access the shared resources in each thread must be placed between Entercritialsection and LeaveCriticalSection. This is a very easy place for beginners to overlook.
#include <windows.h>class ctlock{ public : Ctlock (); ~ctlock (); Critical_section M_cs; // void Lock () {Entercriticalsectio N ( &m_cs); } inline void Unlock () {leavecriticalsec tion ( &m_cs); } }; Ctlock::ctlock () {initializecriticalsection ( &m_cs);} Ctlock:: ~ctlock () {deletecriticalsection ( & m_cs);
Windows version of the thread lock