c++ - 产生一个线程本身是否提供内存顺序保证?
问题描述
我想大致这样做:
初始线程:
- 将一些值写入全局变量(它们将永远不会被再次写入)
- 这可能是中等大小的数据(数组、字符串等)。不能简单地做出来
std::atomic<>
。
- 这可能是中等大小的数据(数组、字符串等)。不能简单地做出来
- 产生其他线程
其他线程:
- 读取全局状态
- 做工作等
现在,我知道我可以将参数传递给std::thread
,但我试图通过这个例子来理解 C++ 的内存保证。
此外,我非常有信心,在任何现实世界的实现中,创建线程都会导致内存屏障,确保线程可以“看到”父线程在此之前编写的所有内容。
但我的问题是:这是由标准保证的吗?
旁白:我想我可以添加一些虚拟std::atomic<int>
的东西,然后在启动其他线程之前写入,然后在其他线程上,在启动时读取一次。我相信所有先发生的机制都会保证先前编写的全局状态是正确可见的。
但我的问题是,如果这样的东西在技术上是必需的,还是线程创建就足够了?
解决方案
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.
推荐阅读
- stm32 - STM32L053 上的 EEPROM 仿真器
- sql - 如何在sql中获取计数为0的列
- android - 如何使用导航从其他片段隐藏主机活动中的视图
- ios - 使用 Flutter 插件作为子框架开发伞式框架
- django - 字段是必需的,即使它已在序列化程序中明确设置为不需要
- python - 如何在数据框中定义df
- amazon-web-services - Terraform 局部变量不适用于我的“或”运算符
- python - abaqus python(2.7版)使用multiprocessing.Pool(),没有响应
- sql-server - 这些简单的 T-SQL 更新语句是否更新相同?
- verilog - uvm 入门,第 11 章,没有为形式参数“父级”指定实际值