![](/img/trans.png)
[英]std::_Atomic_thread_fence (with capital A) is this correct?
[英]Is this use of std::atomic_thread_fence correct?
我想在構造函數中初始化一個字段,然后再也不要更改它。 我希望保證在構造函數完成后,每次讀取字段都會讀取初始化值,無論讀取發生在哪個線程中。
基本上,我想要與Java中的final
字段相同的保證。
這是我試過的:
#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
或可以跟帖t
觀察foo.x
未初始化狀態? x(x)
而是使用顯式賦值而不是x(x)
this->x = x;
用來? x
不是int
而是某些類類型怎么辦? x
為const int
改變線程安全嗎? 基本上,如果其他一切都是正確的,那么應該沒有任何問題。 在初始化字段之后,在任何線程中訪問它之前,您需要某種內存同步; 這很清楚。 否則,其他線程如何知道它是構造的。 如果在啟動其他線程之前初始化它,那么創建線程將確保必要的同步。 (這只存在於執行創建的線程和創建的線程之間。其他已經運行的線程不同步。)之后,只要沒有線程修改該值,就不需要同步。
關於代碼,您不需要fence,因為在創建任何其他線程之前初始化值,並且創建線程可確保必要的同步。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.