竞争条件如何“未定义”? [英] How 'undefined' a race condition can be?

查看:156
本文介绍了竞争条件如何“未定义”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说定义一个以下的C ++对象:

  class AClass 
{
public:
AClass():foo(0){}
uint32_t getFoo(){return foo; }
void changeFoo(){foo = 5; }
private:
uint32_t foo;
} aObject;

对象由两个线程T1和T2共享。 T1在一个循环中不断地调用 getFoo()以获得一个数字(如果 changeFoo()以前没有调用)。在某些时候,T2调用 changeFoo()来更改它(没有任何线程同步)。



实用机会:T1获得的值与现代计算机体系结构和编译器不同的是0或5?到目前为止,我研究的所有汇编代码都使用32位内存读写,这似乎保存了操作的完整性。



其他原始类型? / p>

实用意味着您可以举一个现有架构或符合标准的编译器,具有不同代码的类似情况)在理论上是可能的。我现在离开这个词有点主观。






>我可以看到许多人注意到,我不应该期望5被阅读。这对我来说是完全正确的,我没有说我做(虽然感谢指出这方面出来)。

解决方案

在实践中,所有主流的32-位体系结构以原子方式执行32位读取和写入。你永远不会看到除0或5之外的任何东西。


Let's say I define a following C++ object:

class AClass
{
public:
    AClass() : foo(0) {}
    uint32_t getFoo() { return foo; }
    void changeFoo() { foo = 5; }
private:
    uint32_t foo;
} aObject;

The object is shared by two threads, T1 and T2. T1 is constantly calling getFoo() in a loop to obtain a number (which will be always 0 if changeFoo() was not called before). At some point, T2 calls changeFoo() to change it (without any thread synchronization).

Is there any practical chance that the values ever obtained by T1 will be different than 0 or 5 with modern computer architectures and compilers? All the assembler code I investigated so far was using 32-bit memory reads and writes, which seems to save the integrity of the operation.

What about other primitive types?

Practical means that you can give an example of an existing architecture or a standard-compliant compiler where this (or a similar situation with a different code) is theoretically possible. I leave the word modern a bit subjective.


Edit: I can see many people noticing that I should not expect 5 to be read ever. That is perfectly fine to me and I did not say I do (though thanks for pointing this aspect out). My question was more about what kind of data integrity violation can happen with the above code.

解决方案

In practice, all mainstream 32-bit architectures perform 32-bit reads and writes atomically. You'll never see anything other than 0 or 5.

这篇关于竞争条件如何“未定义”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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