代码改变世界

c++ unique_lock lock_guard

2016-01-24 22:52  youxin  阅读(1988)  评论(0编辑  收藏  举报

 

unique_lock

template <class Mutex> class unique_lock;
Unique lock

unique lock is an object that manages a mutex object with unique ownership in both states: locked and unlocked.

On construction (or by move-assigning to it), the object acquires a mutex object, for whose locking and unlocking operations becomes responsible.

The object supports both states: locked and unlocked.

This class guarantees an unlocked status on destruction (even if not called explicitly). Therefore it is especially useful as an object with automatic duration, as it guarantees the mutex object is properly unlocked in case an exception is thrown.

Note though, that the unique_lock object does not manage the lifetime of the mutex object in any way: the duration of the mutex object shall extend at least until the destruction of the unique_lock that manages it.

http://www.cplusplus.com/reference/mutex/unique_lock/

<mutex> 头文件介绍

Mutex 系列类(四种)

  • std::mutex,最基本的 Mutex 类。
  • std::recursive_mutex,递归 Mutex 类。
  • std::time_mutex,定时 Mutex 类。
  • std::recursive_timed_mutex,定时递归 Mutex 类。

Lock 类(两种)

  • std::lock_guard,与 Mutex RAII 相关,方便线程对互斥量上锁。
  • std::unique_lock,与 Mutex RAII 相关,方便线程对互斥量上锁,但提供了更好的上锁和解锁控制。
// unique_lock example
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::unique_lock

std::mutex mtx;           // mutex for critical section

void print_block (int n, char c) {
  // critical section (exclusive access to std::cout signaled by lifetime of lck):
  std::unique_lock<std::mutex> lck (mtx);
  for (int i=0; i<n; ++i) { std::cout << c; }
  std::cout << '\n';
}

int main ()
{
  std::thread th1 (print_block,50,'*');
  std::thread th2 (print_block,50,'$');

  th1.join();
  th2.join();

  return 0;
}
Edit & Run

 

 

一篇文章:

boost库中thread多线程详解3——细说lock_guard

boost::lock_guard可以说是一种比boost::unique_lock轻量级的lock, 简单一些场景可以用它就行了。
看看它的源代码也很简单:

template<typename Mutex>
class lock_guard
{
private:
    Mutex& m;

    explicit lock_guard(lock_guard&);
    lock_guard& operator=(lock_guard&);
public:
    explicit lock_guard(Mutex& m_):
        m(m_)
    {
        m.lock();
    }
    lock_guard(Mutex& m_,adopt_lock_t):
        m(m_)
    {}
    ~lock_guard()
    {
        m.unlock();
    }
};


      可以看到只有两个public方法,即构造和析构函数,也就是说,使用boost::lock_guard去guard一个mutex,必然是在boost::lock_guard的对象离开其作用域时unlock它所guard的mutex,不提供提前unlock的功能。
      而boost::unique_lock则提供这个功能,除了像boost::lock_guard一样在离开作用域时unlock它guard的mutex外,boost::unique还提供unlock函数,使用者可以手动执行unlock。此外,unique_lock还可以设置超时。