2

As I understand it, when I have a collection of threads protected by a std::lock_guard or std::unique_lock over std::mutex and the mutex is unlocked by either explicitly unlocking it or by the lock going out of scope, then the waiting threads are notified.

Is this notification a notify_one or a notify_all?

I suspect the former to avoid hurry up and wait but would like to be sure.

skypjack
  • 49,335
  • 19
  • 95
  • 187
Brenton Thomas
  • 618
  • 1
  • 7
  • 17
  • Only one thread can have a mutex locked at a time. When the mutex is unlocked, only one thread is allowed to lock it again. If you have multiple threads waiting for the unlock at the same time, only one thread will gain the new lock, but there is no guarantee of which thread that will be. – Remy Lebeau May 27 '16 at 02:06
  • 3
    The question makes no sense because `notify_one` and `notify_all` are features of `std::condition_variable` not `std::mutex`. – Raymond Chen May 27 '16 at 03:34
  • I meant the same sort of mechanic. Is there an internal list and precisely one gets notified. Or does it simply wake everything up and lets them fight it out for themselves. – Brenton Thomas May 27 '16 at 04:46
  • The standard does not require any particular implementation. All the standard requires is that at the end of the operation, one thread ends up with the mutex lock, and the others are still waiting. – Raymond Chen May 27 '16 at 05:23

2 Answers2

2

What you seem to be asking is whether, when thread T0 has locked mutex M, and threads T1..Tn are blocked attempting to lock M, what happens when T0 unlocks M? Obviously only one thread can successfully lock M, so there would be no reason for the system to "notify" (i.e. schedule) more than one waiter. However, your question is not specific to any one platform, so the answer might have to be "it's implementation dependent."

Fahad Siddiqui
  • 1,829
  • 1
  • 19
  • 41
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
2

It depends on the implementation. The waiting threads could be actively waiting in the user space inside of the mutex::lock() call context for some short time for the mutex to be unlocked and once it's unlocked several actively waiting threads could detect it at the same time but only one would be able to lock it. Otherwise after the active period is passed mutex.lock() issues a system call and OS puts the thread into waiting list for that mutex. When it's unlocked only one thread gets awaken/notified to obtain a lock.

Mikhail Volskiy
  • 209
  • 2
  • 5