[英]C++ Acquire/Release Ordering
假設我有一個從2開始的計數器,一些非原子的布爾變量和4個線程。
//Initialization (happens before any thread execute).
std::atomic<int> count = ATOMIC_VAR_INIT(2);
bool someBoolean = false;
線程1:
count.fetch_sub(1, std::memory_order_release);
線程2:
someBoolean = true;
count.fetch_sub(1, std::memory_order_release);
線程3:
while(count.load(std::memory_order_acquire) != 0);
//Now, we're out of the while loop...
assert(someBoolean);
線程4:
while(std::atomic_thread_fence(std::memory_order_acquire),
count.load(std::memory_order_relaxed) != 0);
//Now, we're out of the while loop...
assert(someBoolean);
線程3或線程4的斷言是否有可能觸發?
線程4可能會觸發該斷言,因為您以錯誤的順序使用load
操作和內存防護。 您必須先load
count
變量,然后放置內存獲取圍欄。
通常,您必須在寫入同步標志之前放置釋放防護,並在讀取后放置獲取隔離。
您可以在偉大的Jeff Preshing的博客中找到這篇文章中有關獲取/釋放內存柵欄的詳細說明和示例: http ://preshing.com/20130922/acquire-and-release-fences/
線程3(和固定函數調用順序后的線程4)將不會觸發斷言,因為線程之間的同步關系已正確建立。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.