Implementation principle of Win32 critical section
Http://www.blogcn.com/user8/flier_lu/index.html? Id = 1205525 & run =. 0748049
In last November, The MSDN magazine published an article Break Free of Code Deadlocks in Critical Sections Under Windows, Matt Pietrek, and Russ Osterlund) I made a brief introduction to the internal implementation of, but I didn't go further until now. At that time, it gave me the feeling that it was itchy, as a result, IDA and SoftIce are used to roughly analyze the implementation of the critical section. After understanding the principle, they will not go further. Now let's take a look at the Win2k source code and analyze the content again. Let's make a small summary: P
The Critical Section is a lightweight synchronization mechanism provided by Win32. Compared with kernel synchronization objects such as Mutex and Event, the critical section is completely maintained in the user state, so it can only be used by threads in the same process. However, you do not need to switch between the user State and the core State during use, work efficiency is much higher than other synchronization mechanisms.
The method of using the critical section is very simple. Use the InitializeCriticalSection or the critical function to initialize a CRITICAL_SECTION structure. Use the internal function to set the Spin counter for the critical section, and then use EnterCriticalSection or TryEnterCriticalSection to get; after completing the operations to be synchronized, use the LeaveCriticalSection function to release the critical section.