Question: A coworker had an issue recently that boiled down to what we believe was the following sequence of events in a C++ application with two threads:

* Thread A holds a mutex.
* While thread A is holding the mutex, thread B attempts to lock it. Since it is held, thread B is suspended.
* Thread A finishes the work that it was holding the mutex for, thus releasing the mutex.
* Very shortly thereafter, thread A needs to touch a resource that is protected by the mutex, so it locks it again.
* It appears that thread A is given the mutex again; thread B is still waiting, even though it "asked" for the lock first.

Does this sequence of events fit with the semantics of, say, C++11's `std::mutex` and/or pthreads? I can honestly say I've never thought about this aspect of mutexes before.

Are there any fairness guarantees to prevent starvation of other threads for too long, or any way to get such guarantees?

Answer: 
Known problem. C++ mutexes are thin layer on top of OS-provided mutexes, and OS-provided mutexes are often not fair. They do not care for FIFO.

The other side of the same coin is that threads are usually not pre-empted until they run out of their time slice. As a result, thread A in this scenario was likely to continue to be executed, and got the mutex right away because of that.
> 
> •Thread A finishes the work that it was holding the mutex for, thus
>  releasing the mutex.
>  •Very shortly thereafter, thread A needs to touch a resource that is
>  protected by the mutex, so it locks it again
> 
> 
> 

In real world, when the program is running. there is no guarantee provided by any threading library or the OS. Here "*shortly thereafter*" may mean a lot to the OS and the hardware. If you say, 2 minutes, then thread B would definitely get it. If you say 200 ms or low, there is no promise of A or B getting it.

Number of cores, load on different processors/cores/threading units, contention, thread switching, kernel/user switches, pre-emption, priorities, deadlock detection schemes et. al. will make a lot of difference. Just by looking at green signal from far you cannot guarantee that you will get it green.

If you want that thread B must get the resource, you may use IPC mechanism to instruct the thread B to gain the resource.