12

为何condition_variable不设计成传入BaseLockable?

 3 years ago
source link: https://www.zhihu.com/question/447453492/answer/1760817376
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
为何condition_variable不设计成传入BaseLockable? - 知乎
登录一下,更多精彩内容等你发现
贡献精彩回答,参与评论互动
C++程序猿, 公众号:高级开发者

标准库里的condition_variable条件变量必须配合 unique_lock 使用,否则编译会报错。unique_lock本身就是一种guard,与lock_guard对比支持加锁、解锁行为。

究其原因是条件变量是在同步等待一个条件,当条件为真时退出等待。具体场景就是一个线程等待条件为真,其他线程在操作,它们需要通信。那么条件等待的那个线程需要释放锁(解锁),因此其他线程有机会拿到锁从而避免竞争状态,当其他线程操作完成时,它们会释放锁同时条件也满足了并进行notify动作,这时候等待条件的那个线程由于条件为真,将退出等待,同时将锁锁上(加锁),继续后面的操作。

简而言之条件变量在wait的时候会释放锁(解锁),条件为真时被notify重新尝试拿到锁(加锁)。因此只有unique_lock满足条件。

另外建议用标准库的promise/future来代替条件变量。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK