Reputation: 1108
Situation:
At this juncture can another thread (say, Thread 3) swoop in and make a request for the lock and acquire it (as shown below)? 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?
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.
Upvotes: 2
Views: 347
Reputation: 239011
There's no such guarantee.
The situation can only arise when Thread 1's unlock is racing with Thread 3's lock, and in that situation there's really no difference between the lock coming slightly before the unlock or slightly after it.
Upvotes: 1
Reputation: 1390
There is no guarantee that the treads will be granted locks in the order they requested them.
Upvotes: 1
Reputation: 5486
At the moment of the unlock all threads that were trying to lock the mutex change state from BLOCKED to READY. A specific implementation may make sure that only one of those threads will get the mutex, but at that point in time any thread may try and lock the mutex.
So Thread 3 may be able to swoop-in and get the mutex before anyone else in some implementations (or maybe even in all of them).
Upvotes: 1