Mutex ownership queue order

2019-02-26 10:25发布

问题:

Say, if I have three threads that all access the same mutually exclusive part via a mutex.

Let me give you this example.

The first thread probes the mutex and gets its ownership first:

//THREAD 1
//TIME: 2013-03-13 01:00:00.000Z
WaitForSingleObject(hMutex, INFINITE);

//Performs the operation that lasts 50 ms

ReleaseMutex(hMutex);

Then 10 ms later the thread 2 also requests it:

//THREAD 2
//TIME: 2013-03-13 01:00:00.010Z
WaitForSingleObject(hMutex, INFINITE);
//Do work
ReleaseMutex(hMutex);

and 20 ms later thread 3 requests it as well:

//THREAD 3
//TIME: 2013-03-13 01:00:00.030Z
WaitForSingleObject(hMutex, INFINITE);
//Do work
ReleaseMutex(hMutex);

In this situation, can I be sure that thread 2 will always get the mutex ownership before thread 3 (since it was "first in line" so to speak), or is it completely arbitrary who gets the ownership between threads 2 and 3?

And if it is arbitrary with mutexes, how to make sure that the first waiting thread gets the ownership first?

回答1:

It's pretty safe to say that for your purpose it's arbitrary in the sense that the operating system will wake up one of the threads waiting for the Mutex and grant it to the thread, but the decision as to which thread is non-deterministic.

You could implement your own scheme for priority between your threads using a global priority index. Then if one of the threads waiting for the Mutex receives it while not being first-in-line it gives it up right away and proceeds to wait until the Mutex becomes available again. This should repeat until the Mutex is acquired and the thread is first-in-line according to the priority index of the thread as compared to the global index.



回答2:

Prior to Vista and Windows Server 2003 SP1 the locking primitives were trying to offer fairness (FIFO). As fairness leads to lock convoys, since Vista and Windows Server 2003 SP1 the locking primitives are explicitly unfair (no FIFO). See Anti-convoy locks in Windows Server 2003 SP1 and Windows Vista and the articles linked.