对条件变量使用锁 [英] Using a lock with condition variables

查看:131
本文介绍了对条件变量使用锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下条件变量的简单示例:

Consider the following simplistic example of condition variables:

bool pause = true;

boost::mutex::scoped_lock lock(m_mutex);
while (!pause) cv.wait(lock);

boost::mutex::scoped_lock lock(m_mutex);
pause = false;
cv.notify_one();

如果我们在支持字节粒度更新的处理器上运行代码,我们是否实质上需要scoped_lock或此处的任何其他锁?从本质上讲,这意味着布尔值的分配是原子的,而x86处理器通常就是这种情况.

Do we essentially need the scoped_lock or any other lock here, if we are running the code on a processor which supports updates on byte-granularity. This essentially means that the assignment of bools are atomic which is typically the case with x86 processors.

当两个线程在两个不同的处理器上运行并且具有单独的缓存时,是否与变量的同步有关?

Has it got something to do with syncing of the variable in the case when the two threads are running on two different processors and have separate caches?

推荐答案

是的,仅使用atomic是不够的.

Yes you do, and using atomic is not sufficient.

提高效率的CV可能被虚假唤醒,而那些虚假的查找(或类似问题)可能会导致写操作丢失.

CVs for efficiency can be woken spuriously, and those spurious lookups (or similar issues) can cause a write to be missed.

想象一下一个虚假的醒来.接收线程检查布尔值,什么也看不到(假),然后被抢占.有人通知所有人并设置布尔值.该通知被丢弃,因为接收线程已经在处理一个.接收线程现在完成,并且错过了消息.

Imagine a spurious wake up. The recieving thread checks the bool, sees nothing (false), then is preempted. Someone notify all's and sets the bool. The notification is discarded, as the recieving thread is already processing one. The recieving thread now completes, and misses the message.

现在,在发送方中添加一个锁定,该锁定与设置布尔值之后和cv通知之前的某个时间重叠.该通信孔不再存在.

Now, add a lock in the sender that overlaps some time sequenced after the bool is set and before the cv notification. This communicaton hole no longer exists.

(即使没有虚假的唤醒,有时多个通知也会引起类似的问题.)

(Even without spurious wakeups, multiple notifications can cause similar problems sometimes.)

您不必在通知时持有该锁(实际上这是一种悲观的说法),但是通常必须在写入后和预先通知一段时间后才持有该锁.

You do not have to hold the lock while notifying (and in fact this is a pessimization), but the lock must be held post-write and pre-notify for some period, in general.

这篇关于对条件变量使用锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆