c++ - 唯一锁和条件变量 - 显式调用解锁

标签 c++ multithreading c++11 std

我找到了一个演示如何使用条件变量的示例代码:

#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/

相关文章:

c++ - Qt:在单独的函数中使用ui指针

c++ - boost::asio 中的 post 和 dispatch 有什么区别?

c++ - C++ 函数 'remainder' 和 'fmod' 之间的区别?

c++ - C++线程连接会立即返回吗?

C++ - 如何在 lldb/Xcode 中获取 std::vector 对象的地址

c++ - C++ 中有没有一种方法可以将一个类的接口(interface)呈现给所有类,除了少数几个?

c++ - 项目中c++源文件改函数后重新编译

multithreading - 同步线程以同时读取不同的资源

Java多线程ConcurrentModificationException

c++ - 最优雅的可变函数