On 2016-08-31, Sibin Thomas <
sibinp...@gmail.com> wrote:
> Situation:
>
> 1. Thread 1 currently owns the mutex.
> 2. While Thread 1 retains ownership of the mutex, Thread 2 makes a request for the same lock.
> 3. Thread 1 unlocks the lock.
>
> At this juncture can another thread (say, Thread 3) swoop in and make
> a request for the lock and acquire it (as shown in the image below)?
This may depend on the mutex attributes. Such a requirement is not
defined for any of the standard mutex types (PTHREAD_MUTEX_NORMAL,
PTHREAD_MUTEX_DEFAULT, etc).
A strict mutex like this could be provided as some platform-specific
type.
A pthread implementation could even map the default type to such
a mutex. (Since that will negatively affect throughput for the sake of
fairness, unlikely).
> Or does POSIX guarantee that a mutex shall be acquired by a thread
> that is already waiting for the said mutex at the moment of unlocking
> a mutex?
>
>
http://i.stack.imgur.com/yy937.png
>
> The man page for `pthread_mutex_unlock()` states that -
>
>> If there are threads blocked on the mutex object referenced by mutex
>> when pthread_mutex_unlock() is called, resulting in the mutex becoming
>> available, the scheduling policy shall determine which thread shall
>> acquire the mutex.
>
> This seems to say that Thread 3 can not swoop in and acquire the mutex, though I am not fully assured.
Yes, on a single processor, the scheduling policy will effectively
decide that, taking into consideration thread priorities. The unlock
operation will wake up a waiting thread. So then in your scenario, you
have three threads which are runnable. The original thread (which is
presumably going off to do something else and not contending for the
mutex), the woken thread, and the opportunistic one. Only one thread at
a time can run on the processor. Between the two threads which want the
mutex, the one that will get it will be the one which runs first, and
that is up to the scheduler.
On a multiprocessor, the opportunistic thread can, however, be actually
executing on one processor as the mutex is unlocked on another
processor, and can perhaps snatch the mutex via an atomic operation not
even involving a trip to the kernel.
The thread which was woken from waiting on the mutex tries the same
atomic operation and finds that it fails.