gpt4 book ai didi

C++ 多线程 : Visible side-effects of non-atomic variables

转载 作者:行者123 更新时间:2023-12-01 14:48:08 24 4
gpt4 key购买 nike

C++ 标准中有一部分关于多线程内存模型我不明白。

A visible side effect A on a scalar object or bit-field M with respect to a value computation B of M satisfies the conditions:

  • A happens before B and

  • there is no other side effect X to M such that A happens before X and X happens before B.

The value of a non-atomic scalar object or bit-field M, as determined by evaluation B, shall be the value stored by the visible side effect A.


而且根据 C++ 标准,线程之间的“发生在”关系必须通过“与”或“依存顺序在前”建立,因此没有线程间同步将不会建立“发生在”关系。
现在假设有两个线程 T1 和 T2,它们都由主线程启动并且彼此之间从不进行任何同步(因此不会在 T1 和 T2 之间建立任何“发生在之前”的关系)。如果 T1 写入 非原子 变量 M,那么根据上面的引用,T2 永远不会看到 M 被 T1 修改,因为 T1 和 T2 之间没有“发生在之前”的关系。
相反,T2在T2启动时与主线程建立了“同步”关系,所以T2应该在主线程启动之前看到主线程设置的M的值,因为有一个“发生在之前”主线程和T2的关系。
对?但是我在我的机器上做了一个实验,但事实并非如此。怎么了?

最佳答案

T1 writes to a non-atomic variable M, then according to the quote above, T2 should never see M modified by T1


考虑以下:

Two actions are potentially concurrent if

  • they are performed by different threads, or

  • they are unsequenced, at least one is performed by a signal handler, and they are not both performed by the same signal handler invocation.


T2 对 M 的读取和 T1 对 M 的写入是“潜在并发的”。下一个:

Two expression evaluations conflict if one of them modifies a memory location and the other one reads or modifies the same memory location.


T2 对 M 的读取与 T1 对 M 的写入发生冲突。因此这些“潜在并发”操作发生冲突。
最后,我们来到:

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.


T2 对 M 的读取不会在 T1 对 M 的写入之前发生,T1 对 M 的写入也不会在 T2 对 M 的读取之前发生。因此,存在数据竞争。
数据竞争是未定义的行为。并不是 T2 不会看到对 M 的写操作;而是它可以看到任何东西:旧值、新值、某个第三值、发出的鼻涕虫,任何东西。

关于C++ 多线程 : Visible side-effects of non-atomic variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61282738/

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