我試圖找出資料競賽的主題,并撰寫了這段代碼。在這里,我們使用共享元素wnd。我認為通過在 while 回圈中放置鎖,我會禁止th1執行緒使用wnd,但這并沒有發生,我看到th1 執行緒的輸出暢通無阻。
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
int main()
{
bool wnd = true;
std::mutex mutex;
std::unique_lock<std::mutex> lock(mutex, std::defer_lock);
std::thread th1([&]() {
int i = 0;
while (true)
{
i;
lock.lock();
if (wnd)
std::cout << i << " WND TRUE" << std::endl;
else
std::cout << i << " WND FALSE" << std::endl;
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
});
while (true)
{
lock.lock();
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
if (wnd)
wnd = false;
else
wnd = true;
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
th1.join();
return 0;
}
說實話,我希望看到th1執行緒在主執行緒位于鎖定部分內時停止列印 2 秒。
uj5u.com熱心網友回復:
您沒有使用互斥鎖并且特別std::unique_lock正確。
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
int main()
{
bool wnd = true;
std::mutex mutex;
std::thread th1{[&]() {
for (int i = 0; i<10000; i)
{ std::unique_lock<std::mutex> lock(mutex);
std::cout << i << "\tWND\t " << std::boolalpha << wnd << std::endl;
};
}};
for (int i = 0; i<30; i)
{ std::unique_lock<std::mutex> lock(mutex);
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
wnd = !wnd;
};
th1.join();
}
std::unique_lock使用它的建構式運算元作為獲取是lock和釋放是的資源unlock。它旨在RAII用作保證互斥鎖上正確鎖定/解鎖序列的一種手段。延遲鎖僅表示互斥鎖在生命周期開始時未鎖定std::unique_lock這不是通常的用例。您可以手動鎖定/解鎖互斥鎖,但這通常會導致代碼的可維護性降低、更容易出錯。請記住,如果所涉及的執行緒沒有爭奪互斥鎖的所有權,則兩者都不會等待另一個;在您的原始程式中,作業執行緒沒有接觸互斥鎖。但是在上面的程式中,兩個執行緒都在競爭鎖定互斥鎖;獲勝者有機會繼續他想做的事情,而失敗者必須等到互斥鎖被解鎖——這樣他才能獲得它的所有權。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/461340.html
