[英]Memory semantics of initialization in multithread environment (C++)
I am not certain of the memory semantics of C++ initialization process. 我不确定C ++初始化过程的内存语义。 Let's say we have the following program. 假设我们有以下程序。
#include <iostream>
#include <thread>
using namespace std;
void func(int* arr, int s)
{
for (int i = 0; i < s; ++i)
{
cout << arr[i] << endl;
}
}
int main(int argc, char *argv[])
{
int *a = new int[10];
for (int i = 0; i < 10; ++i)
{
a[i] = i;
}
// Do I need some sort of memory barrier here?
std::thread t(func, a, 10);
t.join();
return 0;
}
Will the new thread see an array initialized properly? 新线程会看到正确初始化的数组吗? Or do I need the insert some sort of memory barrier in between. 还是我需要在两者之间插入某种内存屏障。 How does C++ language define the memory semantics for the initialization? C ++语言如何定义初始化的内存语义?
My concern is that all the writes to array a[10] may sit in one cpu's write buffer, and we start a new thread on a different cpu, which may not observe the initialization writes. 我担心的是,所有对数组a [10]的写操作都可能位于一个cpu的写缓冲区中,而我们在另一个cpu上启动了一个新线程,这可能不会观察到初始化写操作。
Do we need memory fence for initialization to be able to be observed by later issued thread running on a different cpus? 我们是否需要内存围栏才能进行初始化,以便在其他cpus上运行的稍后发布的线程能够观察到该初始化?
There is a "happens-before" relationship between operations in the parent prior to executing the thread constructor, and the thread procedure running in the child. 在执行线程构造函数之前,父级中的操作与子级中运行的线程过程之间存在“先发制人”的关系。 In particular the Standard says ( f
being the thread procedure): 特别是标准说( f
是线程过程):
Synchronization : The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of
f
. 同步 :构造函数调用的完成与f
副本的调用的开始同步。
This is found in section [thread.thread.constr]
这可以在[thread.thread.constr]
部分中找到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.