It\'s written in POSIX threads tutorial https://computing.llnl.gov/tutorials/pthreads/ that it is a logical error.
my question is why it is a logical error?
A condition variable allows one thread to wake another up from a wait. They work only if there is a thread waiting at the moment when you trigger the condition. The way to ensure that this is the case is for the waiting thread to lock a mutex which is linked to the condition, and for the signalling thread to lock that mutex before triggering the condition. In other words, the signalling thread can only lock the mutex and trigger the condition if the other thread had the mutex locked but is now waiting.
I'm most familiar with boost, so I'll use that in this example:
// A shared mutex, global in this case.
boost::mutex myMutex;
// Condition variable
boost::condition_variable myCondition;
void threadProc()
{
// Lock the mutex while the thread is running.
boost::mutex::scoped_lock guard( myMutex );
while( true )
{
// Do stuff, then...
myCondition.wait( guard ); // Unlocks the mutex and waits for a notification.
}
}
void func()
{
// Function wants to trigger the other thread. Locks the mutex...
boost::mutex::scoped_lock guard( myMutex );
// Since the mutex is locked, we know that the other thread is
// waiting on the condition variable...
myCondition.notify_all();
}
To signal a condition variable when there is no corresponding wait is a logical error because nothing will ever receive the signal. Condition variables don't remain in a signalled state.