通知的条件变量在收到通知后重新锁定互斥锁的原因是什么
如果unique_lock没有作用域或互斥体未明确解锁,则以下代码会死锁
#include <future>
#include <mutex>
#include <iostream>
using namespace std;
int main()
{
std::mutex mtx;
std::condition_variable cv;
//simulate another working thread sending notification
auto as = std::async([&cv](){ std::this_thread::sleep_for(std::chrono::seconds(2));
cv.notify_all();});
//uncomment scoping (or unlock below) to prevent deadlock
//{
std::unique_lock<std::mutex> lk(mtx);
//Spurious Wake-Up Prevention not adressed in this short sample
//UNLESS it is part of the answer / reason to lock again
cv.wait(lk);
//}
std::cout << "CV notified\n" << std::flush;
//uncomment unlock (or scoping above) to prevent deadlock
//mtx.unlock();
mtx.lock();
//do something
mtx.unlock();
std::cout << "End may never be reached\n" << std::flush;
return 0;
}
即使重新阅读some documentation and examples,我仍然看不到这一点。
在网络上可以找到的大多数示例是具有固有锁唯一范围的小型代码示例。
我们应该使用不同的互斥量来处理关键部分(互斥量1),而条件变量等待并通知(互斥量2)吗?
注意:调试显示,在等待阶段结束之后,“内部”“互斥计数”(我认为字段__count的结构__pthread_mutex_s)从1变为2。解锁后返回0。