Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you don't reacquire the locking object, how can the threads know that they are done waiting? What will tell them that? Returning from the block tells them nothing because the blocking object is stateless. It doesn't have an "unlocked" or "not blocking" state for it to return in.</p> <p>You have to pass some data to them, otherwise how will they know that before they had to wait and now they don't? A condition variable is completely stateless, so any state that you need must be maintained and passed by you.</p> <p>One common pattern is to use a mutex, condition variable, and a state integer. To block, do this:</p> <ol> <li><p>Acquire the mutex.</p></li> <li><p>Copy the value of the state integer.</p></li> <li><p>Block on the condition variable, releasing the mutex.</p></li> <li><p>If the state integer is the same as it was when you coped it, go to step 3.</p></li> <li><p>Release the mutex.</p></li> </ol> <p>To unblock all threads, do this:</p> <ol> <li><p>Acquire the mutex.</p></li> <li><p>Increment the state integer.</p></li> <li><p>Broadcast the condition variable.</p></li> <li><p>Release the mutex.</p></li> </ol> <p>Notice how step 4 of the locking algorithm tests whether the thread is done waiting? Notice how this code tracks whether or not there has been an unblock since the thread decided to block? You have to do that because condition variables don't do it themselves. (And that's why you need to reacquire the locking object.)</p> <p>If you try to remove the state integer, your code will behave unpredictably. Sometimes you will block too long due to missed wakeups and sometimes you won't block long enough due to spurious wakeups. Only a state integer (or similar predicate) protected by the mutex tells the threads when to wait and when to stop waiting.</p> <p>Also, I haven't seen how your code uses this, but it almost always folds into logic you're already using. Why did the threads block anyway? Is it because there's no work for them to do? And when they wakeup, are they going to figure out what to do? Well, finding out that there's no work for them to do and finding out what work they do need to do will require some lock since it's shared state, right? So there almost always is already a lock you're holding when you decide to block and need to reacquire when you're done waiting.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload