Reference: http://blog.csdn.net/leeds1993/article/details/52738845
What is False awakening?
For example, we now have a producer-consumer queue and three threads.
The I.1 line takes an element from the queue and the queue becomes empty.
The II.2 line also wants to get an element from the queue, but at this point the queue is empty, and line Line 2 can only go into blocking (cond.wait ()), waiting for the queue to be non-empty.
Iii. at this point, line Line 3 will queue an element and invoke the Cond.notify () wake-up condition variable.
Iv. the waiting state of line Line 2 receives a wake-up signal of line Line 3, ready to unblock and perform the next task (getting the elements in the queue).
V. However, such a situation may occur: when the line Line 2 is ready to get the queue's lock, to get the elements in the queue, then the Line 1 line process just finished the element operation, return to the request queue elements, Line 1 line to get the queue lock, check the queue is not empty, get to the Line 3 route just queued elements, and then release the queue lock.
Vi. wait until the Line 2 line to get the queue lock, the discovery queue is still empty, Line 1 line "stole" this element, so for the Line 2 line, this wake is "false", it needs to wait for the queue again non-empty.
use while () to determine why
Under a multicore processor, pthread_cond_signal may activate more than one thread (the thread that is blocking the condition variable). The result is that when a thread calls Pthread_cond_signal (), multiple calls to Pthread_cond_wait () or pthread_cond_timedwait () are returned. This effect is called "false Awakening".
Note: pthread_cond_wait This function is a single atomic operation, that is, two actions of this function: unlocking && entering block is an atomic operation.
"Turn" pthread_cond_signal false wake-up problem