std::thread::join 是否保证写入可见性

Does std::thread::join guarantee writes visibility

Std::thread::join 据说是 'synchronize-with' 加入的线程,但是同步并没有说明副作用的可见性,它只是控制可见性的顺序,即。在以下示例中:

int g_i = 0;
int main()
{
  auto fn = [&] {g_i = 1;};
  std::thread t1(fn);
  t1.join();
  return g_i;
}

我们是否c++ 标准保证此程序始终return 1?

在线程执行完成之前,

t1.join() 不会 return,因此根据您的示例,g_i 保证为 1

[thread.thread.member]:

void join();
Effects: Blocks until the thread represented by *this has completed.
Synchronization: The completion of the thread represented by *this synchronizes with the corresponding successful join() return.

由于线程执行的完成与thread::join同步return,所以线程inter-thread happens before的完成与return:

An evaluation A inter-thread happens before an evaluation B if
A synchronizes with B

因此happens before它:

An evaluation A happens before an evaluation B (or, equivalently, B happens after A) if:
A inter-thread happens before B

由于(线程间)发生在传递性之前(让我跳过复制粘贴线程间发生之前的整个定义以显示这一点),线程完成之前发生的所有事情,包括值的写入1g_i,发生在 thread::join 的 return 之前。 thread::join 中的 return 又发生在 return g_i; 中读取 g_i 的值之前,因为 thread::join 的调用顺序在 [=20] 之前=].同样,使用传递性,我们确定在非主线程中将 1 写入 g_i 发生在主线程中 return g_i; 中读取 g_i 之前。

1写入g_i相对于在return g_i;中读取g_ivisible side effect

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.

最后一句的强调是我的,它保证从 return g_i; 中的 g_i 读取的值将是 1