gpt4 book ai didi

c++ - 用另一个活跃变量保护一个活跃变量安全吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:26:00 26 4
gpt4 key购买 nike

void foo(volatile int& a, volatile int& b, bool threadOne) {
if (threadOne) {
//EDIT: switched the following two lines
b = 10;
a = 5;
} else {
while(a == 0);
cout << a << b;
}
}

//somewhere else
int a = 0;
int b = 0;
std::thread th1(foo, a, b, true);
std::thread th2(foo, a, b, false);

这在 x86 上是否安全,即根据 c++ 标准和 x86 引用的每个合法交错指令都会打印“510”?我的假设是它实际上是安全的。

最佳答案

§1.10 [intro.multithread](引用 N4140):

6 Two expression evaluations conflict if one of them modifies a memory location (1.7) and the other one accesses or modifies the same memory location.

23 Two actions are potentially concurrent if

  • they are performed by different threads, or
  • they are unsequenced, and at least one is performed by a signal handler.

The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, except for the special case for signal handlers described below. Any such data race results in undefined behavior.

您的一个线程从 a 读取,另一个线程写入 a,两者都不是原子的,并且这两个潜在的并发冲突操作都不会先于另一个发生。因此,您会遇到数据竞争和未定义的行为。

关于c++ - 用另一个活跃变量保护一个活跃变量安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27024904/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com