I will try to add a little more explanation regarding WHY variables that require locking.
You must have a lock because your code must verify that the condition predicate is true. A predicate is a value or combination of values ββthat must be true in order to continue. It can be a pointer that is NULL or points to a ready-made data structure, ready for use.
You must block it and CHECK the predicate before waiting, because by the time you start waiting for another thread, you may already have installed it.
A status notification and return of a wait DOES NOT mean that the condition is true. It only means that the condition WAS true at some time. Perhaps this was even true, then false, and then true. It could also mean that your thread was in an unrelated signal handler, which caused a wait state. Your code does not even know how many times a status notification has been called.
So, as soon as the wait condition returns it, the LOCKS mutex. Now your code can check the status, safely in the lock. If true, then the code can update what it needs to update and release the lock. If this is not true, it simply reverts to a wait state to retry. For example, it can take a pointer to a data structure and copy it into a vector, and then set the lock-protected pointer back to NULL.
Think about the condition to make the polling cycle more efficient. Your code still needs to do everything that it will do in anticipation of the loop, except that it can go into sleep mode instead of continuous rotation.
source share