我找到了一个演示如何使用条件变量的示例代码:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <deque>
using namespace std;
deque<int> qu;
mutex mu;
condition_variable cond;
void fun1()
{
int count = 100;
while (count > 0)
{
unique_lock<mutex> locker(mu);
qu.push_front(count);
locker.unlock(); // explicit unlock 1
cond.notify_one();
--count;
}
}
void fun2()
{
int data = 0;
while(data != 1)
{
unique_lock<mutex> locker(mu);
cond.wait(locker, [](){ return !(qu.empty()); });
data = qu.back();
qu.pop_back();
locker.unlock(); // explicit unlock 2
cout<<"data: "<<data<<endl;
}
}
int main()
{
thread t1(fun1);
thread t2(fun2);
t1.join();
t2.join();
system("pause");
return 0;
}
我认为没有必要显式调用解锁。但是,在 fun1 中,在 notify_one 之前调用它可能会提高性能,对吧?为什么 unlock 在 fun2 中被调用(在每次迭代中 unlock 被隐式调用,所以明确地这样做是没有意义的)?
最佳答案
std::unique_lock 使用 RAII 模式。
这意味着它不需要在互斥量上显式调用解锁。这提供了异常安全性,即在锁定互斥锁之后和显式解锁它之前发生异常的情况下,它会在超出范围时自动解锁。
关于c++ - 唯一锁和条件变量 - 显式调用解锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26345779/