Condition Variable notify_one notify_all

来源:互联网 发布:mac word批量导入图片 编辑:程序博客网 时间:2024/05/10 19:56

多线程中条件变量的notify_one() 与 notify_all()


wait 和 notify (notify_one/notify_all) 配对使用。 

“Notify one: Unblocks one of the threads currently waiting for this condition.If no threads are waiting, the function does nothing.”

“But certain implementations may produce spurious wake-up calls without any of these functions being called. Therefore, users of this function shall ensure their condition for resumption is met.”

notify是通知一个线程获取锁,notifyAll是通知所有相关的线程去竞争锁。
notify不能保证获得锁的线程真正需要锁,并且因此可能产生死锁。

notify()和notifyAll()都是Object对象用于通知处在等待该对象的线程的方法。

两者的最大区别在于:

notifyAll使所有原来在该对象上等待被notify的线程统统退出wait的状态,变成等待该对象上的锁,一旦该对象被解锁,他们就会去竞争。


notify则文明得多他只是选择一个wait状态线程进行通知,并使它获得该对象上的锁,但不惊动其他同样在等待被该对象notify的线程们,当第一个线程运行完毕以后释放对象上的锁此时如果该对象没有再次使用notify语句,则即便该对象已经空闲,其他wait状态等待的线程由于没有得到该对象的通知,继续处在wait状态(直到这个对象发出一个notify或notifyAll,它们等待的是被notify或notifyAll,而不是锁)。




0 0
原创粉丝点击