关于lock_guard

lock_guard的官方解释请参考:http://www.cplusplus.com/reference/mutex/lock_guard/

lock guard is an object that manages a mutex object by keeping it always locked.

On construction, the mutex object is locked by the calling thread, and on destruction, the mutex is unlocked. It is the simplest lock, and is specially useful as an object with automatic duration that lasts until the end of its context. In this way, it guarantees the mutex object is properly unlocked in case an exception is thrown.

Note though that the lock_guard 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 lock_guard that locks it.

lock_guard这个类是互斥量mutex的包装类,用来提供自动为互斥量上锁和解锁,简化多线程编程。我们的 lock_guard 只是一个包装类,而实际的加锁和解锁的操作都还是 std::mutex 完成的。

斥类的最重要成员函数是lock()和unlock()。在进入临界区时,执行lock()加锁操作,如果这时已经被其它线程锁住,则当前线程在此排队等待。退出临界区时,执行unlock()解锁操作。更好的办法是采用”资源分配时初始化”(RAII)方法来加锁、解锁,这避免了在临界区中因为抛出异常或return等操作导致没有解锁就退出的问题。极大地简化了程序员编写mutex相关的异常处理代码。C++11的标准库中提供了std::lock_guard类模板做mutex的RAII。

lock_guard对象并不负责管理mutex对象的生命周期,lock_guard对象只是简化了mutex对象的上锁和解锁操作,方便线程对互斥量上锁,即在某个lock_guard对象的生命周期内,它所管理的锁对象会一直保持上锁状态;而lock_guard的生命周期结束之后,它所管理的锁对象会被解锁。std::lock_guard在构造时只被锁定一次,并且在销毁时解锁。

关于lock_guard的作用域问题:

如果是栈内存,也其作用域是其最近的一对花括号,如果是堆内存,其生命周期取决于手动释放的时机,总之,就是和普通对象的生命周期相同。构造的时候加锁,析构的时候自动释放。

C++中普通对象的生命周期:

       其实也就是对象的作用域问题。c++中,对象的作用域是通过花括号来界定的。在花括号之内定义的变量,在花括号结束的时候就会析构掉,花括号之内称为块作用域。

如下官方的例子:

/ lock_guard example
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::lock_guard
#include <stdexcept>      // std::logic_error

std::mutex mtx;

void print_even (int x) {
  if (x%2==0) std::cout << x << " is even\n";
  else throw (std::logic_error("not even"));
}

void print_thread_id (int id) {
  try {
    // using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:
    std::lock_guard<std::mutex> lck (mtx); 
    print_even(id);
  } //lck这个对象会在代码执行的这里的时候析构,也就意味着,会在这里对mtx进行解锁。lck保护的区域其实就是print_even整个函数执行期间。
  catch (std::logic_error&) {  //在这种临界区会发生异常的情况下使用lock,与unlock可能导致无法解锁,产生死锁。
    std::cout << "[exception caught]\n";
  }
}

int main ()
{
  std::thread threads[10];
  // spawn 10 threads:
  for (int i=0; i<10; ++i)
    threads[i] = std::thread(print_thread_id,i+1);

  for (auto& th : threads) th.join();

  return 0;
}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值