C++并发之锁(std::lock_guard,std::unique_lock)

1 概述

  锁保护是通过使互斥对象始终处于锁定状态来管理互斥对象的对象。。
  在构造时,互斥对象被调用线程锁定,在析构时,互斥被解锁。它是最简单的锁,作为一个具有自动持续时间的对象特别有用,该对象会持续到其上下文结束。通过这种方式,它可以保证互斥对象在抛出异常时正确解锁。
  但请注意,lock_guard对象不会以任何方式管理互斥对象的生存期:互斥对象的持续时间应至少延长到锁定它的lock_guad被析构为止。
  唯一锁是一个在锁定和未锁定两种状态下管理具有唯一所有权的互斥对象的对象。
  在构造时(或通过对其进行移动赋值),对象获取一个互斥对象,由其锁定和解锁操作负责。
  对象支持两种状态:锁定和解锁。
  这个类保证销毁时的解锁状态(即使没有显式调用)。因此,作为一个具有自动持续时间的对象,它特别有用,因为它可以确保互斥对象在抛出异常时正确解锁。
  不过,请注意,unique_lock对象不会以任何方式管理互斥对象的生存期:互斥对象的持续时间应至少延长到管理它的unique_lock析构为止。
其类图如下:
在这里插入图片描述

2 使用实例

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

    void print_no_use_lock(std::mutex & mutex, int x)
    {
   
        try
        {
   
            mutex.lock();
            print_even(x);
            counter++;
            mutex.unlock();
        }
        catch(const std::logic_error& e)
        {
   
            mutex.unlock();
            std::cerr << e.what() << '\n';
        }
    }

    void print_use_lock_guard(std::mutex & mutex, int x)
    {
   
        try
        {
   
            std::lock_guard<std::mutex> lock(mutex);
            print_even(x);
            counter++;
        }
        catch(const std::logic_error& e)
        {
   
            std::cerr << e.what() << '\n';
        }
    }
    void print_use_unique_lock(std::mutex & mutex, int x)
    {
   
        try
        {
   
            std::unique_lock<std::mutex> lock(mutex);
            print_even(x);
            counter++;
        }
        catch(const std::logic_error& e)
        {
   
            std::cerr << e.what() << '\n';
        }
    }
};

void LocksSuite::lock_guard()
{
   
    std::thread threads[10];
    Function4Lock function;
    std::mutex mutex;

    function.counter = 0;
    for(int i = 0; i < 10; i++)
        threads[i] = std::thread(&Function4Lock::print_no_use_lock, 
            std::ref(function), std::ref(mutex), i + 1);
    for(auto & thread: threads)
        thread.join();
    TEST_ASSERT_EQUALS(true, function.counter == 5)

    function.counter = 0;
    for(int i = 0; i < 10; i++)
        threads[i] = std::thread(&Function4Lock::print_use_lock_guard, 
            std::ref(function), std::ref(mutex), i + 1);
    for(auto & thread: threads)
        thread.join();
    TEST_ASSERT_EQUALS(true, function.counter == 5)

    function.counter = 0;
    for(int i = 0; i < 10; i++)
        threads[i] = std::thread(&Function4Lock::print_use_unique_lock, 
            std::ref(function), std::ref(mutex), i + 1);
    for(auto & thread: threads)
        thread.join();
    TEST_ASSERT_EQUALS(true, function.counter == 5)
}

说明:

  • print_no_use_lock不使用锁管理互斥对象,代码复杂不少,如果程序有多种异常及多个分支代码会更复杂。
  • print_use_lock_guard 使用std::lock_guard管理互斥对象,代码简洁很多,在异常情况下和多分支情况下,std::lock_guard的析构函数会自动释放锁。
  • print_use_unique_lock 使用std::unique_lock(不带参数构造)管理互斥对象, 功能与std::lock_guard相同。

std::unique_lock可以构造4种类型锁:

  • normal 构造函数中调用lock加锁,析构函数调用unlock解锁
  • try_to_lock 构造函数中调用try_lock加锁,通过函数owns_lock判断释放锁定,析构函数如果锁定调用unlock解锁
  • defer_lock 在构造函数中不锁定,通过调用lock/try_lock/try_lock_for/try_lock_unti来加锁,析构函数如果锁定调用unlock解锁。
  • adopt_lock 在构造函数中不锁定, 假设在构造之前mutex已加锁,析构函数调用unlock解锁

3 接口使用

3.1 lock_guard

void LocksSuite::lock_guard()
{
   
    std::thread threads[10];
    Function4Lock function;
    std::mutex mutex;

    function.counter = 0;
    for(int i = 0; i < 10; i++)
        threads[i] = std::thread(&Function4Lock::print_no_use_lock, 
            std::ref(function), std::ref
  • 20
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flysnow010

你的鼓励就是我最大的创作动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值