为了便于理解,画了个图,一系列动作完成下来只需要一个mutex和一个conditional_variable。
wait函数包含了很多操作,在wait之前和之后必须要手动加锁/解锁mutex,保证同一时间只有一个人对条件变量cond进行使用。
先unlock或者先发送signal()都可以,Linux推荐吧signal()包在中间。
注意,即便以及发送了signal,却没有unlock,那么及时wait收到了信号,也无法返回,因为wait最后还需要锁住mutex,没抢到的话,只能在那继续阻塞。
pthread conditional_variable:
cond_wait: (usage:) lock -> cond_wait -> unlock
(在调用wait时阻塞住线程,等待cond_signal的通知)
What's inside the function wait()? It unlocks the mutex and then blocks the thread.
The purpose of lock is to prevent simultaneous requests of wait().
If cond_signal happens, it will stop blocking and lock the mutex automatically.
cond_signal: (usage:) lock -> cond_signal -> unlock
here, lock and unlock means you have to write them explicitly in code by using pthread_mutex_lock