notify_one()
of C++ 11 thread library is used to unblock one of the waiting threads.
How does it choose which thread to unblock?
To begin with, I tried googling but could not find any appropriate answer (even on Stack Exchange network), though I read somewhere that the selection of thread is "unspecified".
So I decided to checkout the C++ specification and referred Section 30.5.1 of November 2014 working draft (available for free), it said
Effects: If any threads are blocked waiting for
*this
, unblocks one of those threads.
Clearly, even the specification does not mention what the selection is based on, then I decided to put up this question.
Best Answer
Arbitrarily. The handles of waiting threads are pushed into a container and on
notify_one
it will pick one, wake it and remove it. Usually the one most easily found in the structure.If you specify that the condition is fair then it's the oldest one. Often selected by keeping an ordered ring buffer that can grow as needed.