// spinlockAcquireRelease.cpp
#include <atomic>
#include <thread>
class Spinlock{
std::atomic_flag flag;
public:
Spinlock(): flag(ATOMIC_FLAG_INIT) {}
void lock(){
while(flag.test_and_set(std::memory_order_acquire) );
}
void unlock(){
flag.clear(std::memory_order_release);
}
};
Spinlock spin;
void workOnResource(){
spin.lock();
// shared resource
spin.unlock();
}
int main(){
std::thread t(workOnResource);
std::thread t2(workOnResource);
t.join();
t2.join();
}
在注釋中說:“如果兩個以上的執行緒使用自旋鎖,鎖方法的獲取語意是不夠的。現在鎖方法是獲取釋放操作。所以第12行的記憶體模型必須改為 std::memory_order_acq_rel。”
為什么這個自旋鎖適用于 2 個執行緒而不適用于 2 個以上的執行緒?導致此自旋鎖出錯的示例代碼是什么?
來源:https ://www.modernescpp.com/index.php/acquire-release-semantic
uj5u.com熱心網友回復:
std::memory_order_acq_rel 不需要。
互斥同步在 2 個執行緒之間。一個釋放資料,另一個獲取資料。
因此,其他執行緒執行釋放或獲取操作是無關緊要的。
如果獲取由獨立的柵欄處理,也許更直觀(和有效):
void lock(){
while(flag.test_and_set(std::memory_order_relaxed) )
;
std::atomic_thread_fence(std::memory_order_acquire);
}
void unlock(){
flag.clear(std::memory_order_release);
}
多個執行緒可以自旋flag.test_and_set,但一個執行緒設法讀取更新的值并再次設定它(在單個操作中).. 只有該執行緒在 while 回圈之后獲取受保護的資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/412308.html
標籤:
下一篇:Spring應用程式沒有關閉
