内存排序问题 [英] Memory ordering issues

查看:139
本文介绍了内存排序问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试验C ++ 0x支持,有一个问题,我想不应该在那里。

I'm experimenting with C++0x support and there is a problem, that I guess shouldn't be there. Either I don't understand the subject or gcc has a bug.

我有以下代码,最初 x y 是相等的。线程1总是先增加 x ,然后增加 y 。两者都是原子整数值,因此增量没有问题。线程2正在检查 x 是否小于 y ,并显示错误消息。

I have the following code, initially x and y are equal. Thread 1 always increments x first and then increments y. Both are atomic integer values, so there is no problem with the increment at all. Thread 2 is checking whether the x is less than y and displays an error message if so.

此代码有时失败,但为什么?这里的问题可能是内存重排序,但是所有原子操作默认是顺序一致的,我没有明确放松那些任何操作。我在x86上编译这个代码,据我所知不应该有任何顺序问题。请解释一下问题是什么?

This code fails sometimes, but why? The issue here is probably memory reordering, but all atomic operations are sequentially consistent by default and I didn't explicitly relax of those any operations. I'm compiling this code on x86, which as far as I know shouldn't have any ordering issues. Can you please explain what the problem is?

#include <iostream>
#include <atomic>
#include <thread>

std::atomic_int x;
std::atomic_int y;

void f1()
{
    while (true)
    {
        ++x;
        ++y;
    }
}

void f2()
{
    while (true)
    {
        if (x < y)
        {
            std::cout << "error" << std::endl;
        }
    }
}

int main()
{
    x = 0;
    y = 0;

    std::thread t1(f1);
    std::thread t2(f2);

    t1.join();
    t2.join();
}

结果可以查看这里

推荐答案

问题可能在于你的测试:

The problem could be in your test:

if (x < y)

线程可以评估 x ,而不是去评估 y until很久以后。

the thread could evaluate x and not get around to evaluating y until much later.

这篇关于内存排序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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