work.bin
work.bin

Reputation: 1108

Is mutex ownership handed off strictly only to threads which have requested for the lock prior to unlocking?

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 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?

MUTEX_acquisition_race

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

Answers (3)

caf
caf

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

Slava Imeshev
Slava Imeshev

Reputation: 1390

There is no guarantee that the treads will be granted locks in the order they requested them.

Upvotes: 1

Naomi
Naomi

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

Related Questions