What happens if a posix mutex is unlocked while multiple threads are blocked on this mutex?

StackOverflow https://stackoverflow.com/questions/23187348

  •  06-07-2023
  •  | 
  •  

Frage

thread 1:
     lock mutex1
     long time operation
     unlock mutex1

thread2:
     lock mutex1
     ...

thread3:
     lock mutex1
     ...

thread4:
     lock mutex1
     ...

threadn:
     lock mutex1
     ...

When thread1 unlocks mutex1, which thread will be woken up? Is there a standard specification for it?

War es hilfreich?

Lösung 2

when thread1 unlock mutex1, which thread will be woken up?

One of the other threads that are currently blocked on the mutex. It is unspecified which of them.

Is there a standard specification for it?

No. Different systems may implement it in different ways. (Some might use a simple fifo order for waking the threads, others might use heuristics for deciding which thread to wake up).

Andere Tipps

When you unlock a posix mutex using pthread_mutex_unlock, if several threads are waiting on the mutex only one of them will wake up.

The documentation states:

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top