将相同的值写入同一存储器位置会导致数据竞争吗? [英] Does writing the same value to the same memory location cause a data race?

查看:111
本文介绍了将相同的值写入同一存储器位置会导致数据竞争吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码,它从多个线程将相同的值写入同一个内存位置:

Consider the following code that writes the same value to the same memory location from multiple threads:

void f(int* buf, int n, int* p) {
    for(int i = 0; i < n; i++)
        buf[i] = i;
    *p = buf[n/2];
}

void g(int* buf, int n) {
    int x1, x2;
    thread t1(f, buf, n, &x1);
    thread t2(f, buf, n, &x2);
    t1.join();
    t2.join();
    assert(x1 == x2);
}

虽然很有趣,但我不太关心什么保证标准,因为我猜它没有。我所关心的是上述代码在真实世界的多处理器硬件上的行为。 assert 总是通过,或者有任何机会出现竞争条件,缓存同步问题等。

Although it's interesting, I'm of less concern of what guarantees the standard gives, since I guess it gives none. What I do care is what will be the behavior of the above code on real-world multiprocessor hardware. Will the assert always pass or there's any chance of a race-condition, cache synchronization problems, etc..?

推荐答案

当一个线程写入的效果可以被另一个线程观察到时,关于多重关注的内存模型。在代码中,你发布的两个线程都将相同的值写入同一个内存位置,所以不管哪个线程的写操作 buf [n / 2]

Memory models with regards to multi-treading concern when the effects of writes made by one thread are observable by another thread. In the code you posted both threads write the same values into the same memory location, so it doesn't matter which thread's write buf[n/2] reads, either will do.

现代处理器使用缓存一致性协议,例如 MESI ,因此当线程并发写入缓冲区时,CPU之间将发送大量消息,以同步保存缓冲区的缓存行,使其运行速度比非并发场景( false sharing effect )。

Modern processors employ cache coherency protocols, such as MESI, so when the threads write to the buffer concurrently there is going to be a lot of messages sent between the CPUs to synchronize the cache lines holding the buffer making it run much slower than in non-concurrent scenario (false sharing effect).

这里如果写入是原子的,无论如何,因为两个线程都将相同的值写入相同的存储器位置。有一个种族,但是哪个线程获胜并不重要,因为即使部分写入,观察值也是一样的。

Here it doesn't matter if the writes are atomic or not, since both threads write the same values to the same memory locations. There is a race, but it doesn't matter which thread wins because the observed values are going to be the same even with partial writes.

这篇关于将相同的值写入同一存储器位置会导致数据竞争吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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