I have noticed that in most examples of condition variables, I see something like:
pthread_cond_signal(&cond, &lock);
pthread_mutex_unlock(&lock);
My question is why it is done in this order. Why is the signal broadcasted first, before the lock is released? If a context switch occurs in between the signal broadcast and the unlocking, the other threads are woken from sleep and will try to access the lock in question, see that it is still locked, and go back into standby, so won't the signal be wasted?
Why is this not a better solution:
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond, &lock);
In this case, the lock is released before the threads that are asleep are woken up, so they will actually be able to access the previously locked data.
Can someone clear up this issue for me?