[英]Is this use of std::atomic_thread_fence correct?
I want to initialize a field in a constructor and never change it afterwards. 我想在构造函数中初始化一个字段,然后再也不要更改它。 I want the guarantee that after the constructor finished, every read of the field reads the initialized value, no matter in which thread the read happens.
我希望保证在构造函数完成后,每次读取字段都会读取初始化值,无论读取发生在哪个线程中。
Basically, I want the same guarantees as a final
field gives in Java. 基本上,我想要与Java中的
final
字段相同的保证。
This is what I tried: 这是我试过的:
#include <atomic>
#include <iostream>
#include <thread>
struct Foo
{
Foo(int x) : x(x)
{
// ensure all writes are visible to other threads
std::atomic_thread_fence(std::memory_order_release);
}
int x;
};
void print_x(Foo const& foo)
{
// I don't think I need an aquire fence here, because the object is
// newly constructed, so there cannot be any stale reads.
std::cout << foo.x << std::endl;
}
int main()
{
Foo foo(1);
std::thread t(print_x, foo);
t.join();
}
1
or can thread t
observe foo.x
in an uninitialized state? 1
或可以跟帖t
观察foo.x
未初始化状态? x(x)
an explicit assignment this->x = x;
x(x)
而是使用显式赋值而不是x(x)
this->x = x;
is used? x
is not an int
but some class type? x
不是int
而是某些类类型怎么办? x
a const int
change anything with regards to thread safety? x
为const int
改变线程安全吗? Basically, if everything else is correct, there shouldn't be any problem. 基本上,如果其他一切都是正确的,那么应该没有任何问题。 After initializing the field, and before accessing it in any thread, you need some sort of memory synchronization;
在初始化字段之后,在任何线程中访问它之前,您需要某种内存同步; that's clear.
这很清楚。 Otherwise, how can the other threads know that it is constructed.
否则,其他线程如何知道它是构造的。 If you initialize it before starting the other threads, then creating the threads will ensure the necessary synchronization.
如果在启动其他线程之前初始化它,那么创建线程将确保必要的同步。 (This only holds between the thread doing the creation, and the created thread. Other already running threads are not synchronization.) After that, as long as no thread modifies the value, no synchronization is needed.
(这只存在于执行创建的线程和创建的线程之间。其他已经运行的线程不同步。)之后,只要没有线程修改该值,就不需要同步。
With regards to your code, you don't need the fence, because the value is initialized before any of the other threads are created, and creating the thread ensures the necessary synchronization. 关于代码,您不需要fence,因为在创建任何其他线程之前初始化值,并且创建线程可确保必要的同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.