如果共享原子变量未在互斥量下修改,则未正确发布 [英] Shared atomic variable is not properly published if it is not modified under mutex

查看:143
本文介绍了如果共享原子变量未在互斥量下修改,则未正确发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 http://en.cppreference.com上阅读关于std :: condition_variable的内容/ w / cpp / thread / condition_variable ,我不明白这一点:


即使共享变量是原子的,必须在
互斥体下修改,才能正确地将修改发布到等待的
线程。


为什么共享的原子变量没有正确发布,如果它没有在互斥量下修改?如何理解此语句?



在另一页 http://en.cppreference.com/w/cpp/atomic/atomic 有一条声明似乎与第一条语句矛盾:


如果一个线程写入一个原子对象,而另一个线程从它读取
,行为是明确定义的(关于
数据竞争的详细信息,请参阅内存模型) / p>


解决方案

请考虑这个例子:

  std :: atomic_bool proceed(false); 
std :: mutex m;
std :: condition_variable cv;

std :: thread t([& m,& cv,& proceed]()
{
{
std :: unique_lock& :mutex> l(m);
while(!proceed){
hardWork();
cv.wait(l);
}
} $ b b});

proceed = true;
cv.notify_one();
t.join();

这里原子共享数据进行而不使用互斥,之后通知发送到条件变量。但是有可能在发送通知的时候,线程 t 不会等待 cv :改为它是在 hardWork()之前检查继续,发现它是假的。通知被遗漏。当 t 完成 hardwork 时,它将恢复等待(可能是永久)。



如果主线程在修改共享数据继续之前锁定了互斥体,则会避免这种情况。

我认为这是在记住的情况下,当说即使共享变量是原子的,它必须在互斥下修改为了正确地发布修改等待线程。


I am reading about std::condition_variable on http://en.cppreference.com/w/cpp/thread/condition_variable and I don't understand this:

Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread.

Why a shared atomic variable is not properly published if it is not modified under mutex? How to understand this statement?

On another page http://en.cppreference.com/w/cpp/atomic/atomic there is a statement that seems to contradict to the the first statement:

If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see memory model for details on data races)

解决方案

Consider this example:

std::atomic_bool proceed(false);
std::mutex m;
std::condition_variable cv;

std::thread t([&m,&cv,&proceed]()
{
    {
        std::unique_lock<std::mutex> l(m);
        while(!proceed) {
            hardWork();
            cv.wait(l);
        }
    }
});

proceed = true;
cv.notify_one();
t.join();

Here the atomic shared data proceed is modified without the use of a mutex, after which notification is sent to the condition variable. But it is possible that at the instant that the notification is sent, the thread t is not waiting on cv: instead it is inside hardWork() having checked proceed just before that and found it to be false. The notification is missed. When t completes hardWork, it will resume the wait (presumably forever).

Had the main thread locked the mutex before modifying the shared data proceed, the situation would have been avoided.

I think this is the situation in mind when saying "Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread."

这篇关于如果共享原子变量未在互斥量下修改,则未正确发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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