簡體   English   中英

std :: atomic是否阻止對原子變量重新排序非原子變量

[英]Does std::atomic prevent reordering of nonatomic variables over the atomic variables

問題很簡單問:如果我有

settings[N_STNGS];//used by many threads  
std::atomic<size_t> current_settings(0);
void updateSettings()//called by single thread  , always the same thread if that is important
{

    auto new_settings = (current_settings+1)%N_STNGS;
    settings[new_settings].loadFromFileSystem(); //line A
    current_settings=new_settings; //line B
}

標准保證A行不會在B行后重新排序嗎? STNGS的用戶是否也會始終看到一致(提交內存可見性可見)數據?

編輯:對於多個讀者線程和非平凡的設置這是否值得麻煩與簡單的靜音相比?

鑒於定義

int settings[N_STNGS];
std::atomic<size_t> current_settings(0);

和線程1執行:

settings[new_settings] = somevalue;  // line A
current_settings=new_settings;       // line B

和線程2執行:

int cur_settings = current_settings;        // line X
int setting_value = settings[cur_settings]; // line Y

然后是,如果線程2的行X讀取new_settings由線程1中的線B寫的,並且不存在其他的修改,以settings[new_settings]由一些代碼我們看不到),線程2被綁定到讀somevalue和無發生未定義的行為。 這是因為所有操作(默認情況下)是memory_order_seq_cst ,釋放 - 寫入(行B)與獲取讀取(行X)同步。 請注意,您需要在線程2中使用兩個語句來獲取索引的原子讀取和值的讀取之間的順序排序關系(而memory_order_consume操作將執行memory_order_consume操作)。

我肯定會用rw-mutex來實現它。

一般的答案是否定的。 如果你小心並且只使用具有memory_order參數的函數並根據你正在做的事情為它傳遞正確的值,那么它可能是肯定的。

(正如其他人所指出的,你的代碼有問題。例如,按值返回原子<>類型對我來說沒有意義。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM