http://hi.baidu.com/melee2009
This article is a very detailed comparison of the differences between the mutex and the critical section.
Both mutexes and critical sections are primarily used to restrict the access of multiple threads (multithread) to global or shared variables, objects, or memory spaces. Here are some of the main similarities and differences (in different places in green).
|
Mutex |
Critical section |
Performance and Speed |
Slow. A Mutex is a kernel object, the execution of a related function (WaitForSingleObject, ReleaseMutex) requires a conversion of user mode to kernel mode (Kernel mode), which typically costs around 600 CPU instruction cycles on x86 processors. |
Fast. The Critical section itself is not a kernel object, and the invocation of the correlation function (entercriticalsection,leavecriticalsection) is generally performed in user mode, and on the x86 processor it is generally only about 9 CPU instruction cycle. Only when the lock you want to acquire is owned by another thread, it degrades into the same way as a mutex, which translates into kernel mode and charges about 600 CPU instruction cycles. |
Can cross process boundaries |
OK |
Not |
Define the wording |
HANDLE hmtx; |
Critical_section CS; |
Initialize the wording of the |
Hmtx= CreateMutex (NULL, FALSE, NULL); |
InitializeCriticalSection (&CS); |
End Clear Spelling |
CloseHandle (HMTX); |
DeleteCriticalSection (&CS); |
How to wait indefinitely |
WaitForSingleObject (HMTX, INFINITE); |
EnterCriticalSection (&CS); |
0 Waiting (status detection) notation |
WaitForSingleObject (hmtx, 0); |
TryEnterCriticalSection (&CS); |
Any time to wait for the wording |
WaitForSingleObject (HMTX, dwmilliseconds); |
Not supported |
The wording of the lock release |
ReleaseMutex (HMTX); |
LeaveCriticalSection (&CS); |
Can be used together to wait for other kernel objects |
Yes (using WaitForMultipleObjects, WaitForMultipleObjectsEx, MsgWaitForMultipleObjects, Msgwaitformultipleobjectsex, etc.) |
Not |
When the thread that owns the lock dies |
The mutex becomes abandoned state, and other waiting threads can get the lock. |
The state of the Critical section is unknown (undefined), and subsequent movements cannot be guaranteed. |
Will you lock yourself up? |
No (repeated calls to the acquired mutex, WaitForSingleObject, will not lock themselves.) But in the end you don't forget to call the same number of ReleaseMutex) |
No (repeated calls to the critical section that you have obtained will not lock yourself entercriticalsection. But in the end you don't forget to call the same number of leavecriticalsection) |
Here are some additions:
L first check your design and change the unnecessary global or shared objects to local objects. The fewer things are in the world, the less likely the problem will be. Every time you use EnterCriticalSection, don't forget to add leavecriticalsection to all of the functions that may be returned.