![](/img/trans.png)
[英]why lock_guard can get an already locked mutex by unique_lock?
[英]why lock_guard can get an already locked mutex by unique_lock? - still questions
我正在研究這個例子 。 我已經找到了這個問題,並認為我會得到答案,但是我仍然有一個問題。
為了方便起見,我將代碼發布在這里:
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;
void worker_thread()
{
// Wait until main() sends data
std::cout << "------------------------\n";
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return ready;});
// after the wait, we own the lock.
std::cout << "Worker thread is processing data\n";
data += " after processing";
// Send data back to main()
processed = true;
std::cout << "Worker thread signals data processing completed\n";
// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lk.unlock();
cv.notify_one();
}
int main()
{
std::thread worker(worker_thread);
data = "Example data";
// send data to the worker thread
{
std::lock_guard<std::mutex> lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one();
// wait for the worker
{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return processed;});
}
std::cout << "Back in main(), data = " << data << '\n';
worker.join();
return 0;
}
語句std::unique_lock<std::mutex> lk(m);
阻塞主線程,因為互斥鎖m
被worker_thread
鎖定了嗎? 如果是,則不是語句cv.wait(lk, []{return processed;});
在這個例子中沒有必要嗎? 當主線程可以鎖定互斥鎖時,已processed
為true。
wait
的調用會在wait
解鎖互斥鎖。 請參閱http://en.cppreference.com/w/cpp/thread/condition_variable/wait 。
編輯:在您鏈接到的問題的答案中明確指出: https : //stackoverflow.com/a/32030975/212870
編輯2:並非“當主線程可以鎖定互斥鎖時,已processed
為真”。 工作線程甚至可能尚未啟動,或者如果尚未啟動,則可能尚未設置ready
。
第cv.wait(lk, []{return ready;});
如果ready
為false
則執行以下操作:
解鎖互斥鎖lk
阻止線程等待通知
通知到達時,取消阻塞線程並鎖定互斥鎖lk
因此,主線程不會在std::lock_guard<std::mutex> lk(m);
上阻塞std::lock_guard<std::mutex> lk(m);
因為互斥鎖是通過工作線程解鎖的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.