On the forum, a netizen asked me about the mutex volume. I made some modifications,CodeAs follows:
Int main () {handle hmutex = createmutex (null, false, null); waitforsingleobject (hmutex, infinite); waitforsingleobject (hmutex, infinite ); printf ("test mutex \ n"); Return 0 ;}
Why is waitforsingleobject not blocked?
Obviously, the second parameter of createmutex is false. The thread ID and recursive count of the mutex kernel object are both 0, that is, the created state is triggered. When a thread calls waitforsingleobject, if the corresponding kernel object is already in the trigger state, the thread will not enter the waiting state. It will only set the thread ID of the kernel object to the call thread ID, set the recursive count to 1. The second call to waitforsingleobject will not be blocked because the mutex kernel object is different from the common kernel object. If the current thread already has a mutex object, call waitforsingleobject again, the system checks whether the invocation thread ID is consistent with the thread ID recorded by the kernel object. If the invocation thread ID is consistent, the invocation thread is still in the schedulable State, even if the mutex is not triggered.
At this point, I wonder if the initial mutex is not triggered, that is, if the second parameter is set to true, will the thread block the first waitforsingleobject? I think yes, because it is waiting for the kernel object to be triggered, I can try it and find that it is not blocked. When createmutex is set to true, the thread ID of the object is set to the thread ID of the calling thread, and the recursive count is set to 1. The subsequent explanations are described above.
Summary:
(1) mutex thread ID is the basis for determining the status of mutex objects. 0 has been triggered, and non-0 has not been triggered.
(2) The same thread waitforsingleobject multiple times the same mutex object. The system determines whether to suspend the thread Based on the mutex object thread ID.