我想知道这段代码是否正确:
#include <iostream>
#include <future>
struct Foo
{
Foo()
:m_a(0)
{
}
int m_a;
};
int main()
{
Foo f;
auto handle =
std::async( std::launch::async,
[](Foo* f) { std::cout << f->m_a << '\n'; } ,
&f
);
handle.get();
}
我认为 m_a
应该受到同步机制的保护,但我的同事说没有必要。
编辑:澄清我的问题:我担心 Foo()
构造函数的 STORE 操作发生在另一个线程的 LOAD 操作之后。我看不出是什么机制阻止编译器按此顺序执行这些指令。
编辑:我相信热心的编译器可能会决定内联构造函数,并将 STORE 操作延迟到 std::async
的 CALL 操作之后。在这种情况下,第二个线程可以在 m_a
提交到内存之前访问它。
最佳答案
是的,这是正确同步的。
来自 async
的规范,C++11 30.6.8/5:
the invocation of
async
synchronizes with the invocation off
.
其中 f
是 async
的函数参数(您示例中的 lambda)。
f.m_a
的初始化顺序在调用 async
之前,因此在异步函数进行任何访问之前。
此外,
the completion of the function f is sequenced before the shared state is made ready.
因此访问必须发生在对 get()
的调用返回之前,因此也发生在对象被销毁之前。
关于c++ - 此代码是否正确同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28148460/