首页 > 解决方案 > 产生一个线程本身是否提供内存顺序保证?

问题描述

我想大致这样做:

初始线程:

其他线程:

现在,我知道我可以将参数传递给std::thread,但我试图通过这个例子来理解 C++ 的内存保证。

此外,我非常有信心,在任何现实世界的实现中,创建线程都会导致内存屏障,确保线程可以“看到”父线程在此之前编写的所有内容。

但我的问题是:这是由标准保证的吗?

旁白:我想我可以添加一些虚拟std::atomic<int>的东西,然后在启动其他线程之前写入,然后在其他线程上,在启动时读取一次。我相信所有先发生的机制都会保证先前编写的全局状态是正确可见的。

但我的问题是,如果这样的东西在技术上是必需的,还是线程创建就足够了?

标签: c++multithreading

解决方案


Thread creation is enough. There is a synchronization point between the thread constructor and the start of the new thread per [thread.thread.constr]/7

Synchronization: The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.

This means that all state in the thread before the new thread is spawned is visible to the spawned thread.


推荐阅读