• 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
  • 相关阅读:
    自动化测试基础知识详解
    【论文笔记之 YIN】YIN, a fundamental frequency estimator for speech and music
    飞书事件订阅的应用
    JWT开发详解
    【Vue3 Antdv】Ant Design Vue文字溢出鼠标滑上显示tooltip。不溢出,鼠标滑上不显示tooltip
    C++深搜例题代码加讲解
    javaweb第一章 mysql数据库
    Springboot流浪动物救助管理系统y7274计算机毕业设计-课程设计-期末作业-毕设程序代做
    C++学习——优先级队列模拟实现与仿函数初步认识
    Idea - 快速生成一个测试方法
  • 原文地址:https://blog.csdn.net/flysnow010/article/details/139633742