其他分享
首页 > 其他分享> > c-正式保证读取的内容在其他线程中不会看到写入(带有竞争条件)的方式是什么?

c-正式保证读取的内容在其他线程中不会看到写入(带有竞争条件)的方式是什么?

作者:互联网

这是关于C标准的形式保证的问题.

当潜在存在竞争条件时,可以保证对共享变量(普通,非原子)的读取看不到写入,从而使两次读取看到两个“后续”(按照程序顺序和条件)写入并导致每次读取导致一次写入,并引起数据竞争:

// Global state
int x = 0, y = 0;

// Thread 1:
r1 = x;
if (r1 == 42) y = r1;

// Thread 2:
r2 = y;
if (r2 == 42) x = 42;

原子对象的标准explicitly says such behavior is allowed by the specification

[Note: The requirements do allow r1 == r2 == 42 in the following
example, with x and y initially zero:

06001

However, implementations should not allow such behavior. – end note]

所谓的“内存模型”的哪一部分保护非原子对象免受这些读取所引起的交互作用?

解决方法:

When a race condition potentially exists, what guarantees that a read of a shared variable (normal, non atomic) cannot see a write

没有这样的保证.

存在竞争条件时,程序的行为是不确定的:

[intro.races]

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.

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. …

特殊情况与该问题不是很相关,但是为了完整起见,我将其包括在内:

Two accesses to the same object of type volatile std::sig_­atomic_­t do not result in a data race if both occur in the same thread, even if one or more occurs in a signal handler. …

标签:stdatomic,c,multithreading,language-lawyer,data-race
来源: https://codeday.me/bug/20191014/1911830.html