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

相关推荐

  1. C++ 并发编程 |

    2024-06-17 08:58:05       26 阅读
  2. C++并发编程】(三)互斥:std::mutex

    2024-06-17 08:58:05       9 阅读
  3. C# 多线程编程:线程与无并发

    2024-06-17 08:58:05       17 阅读
  4. 并发编程】

    2024-06-17 08:58:05       36 阅读
  5. 并发中的

    2024-06-17 08:58:05       21 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-17 08:58:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-17 08:58:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-17 08:58:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-17 08:58:05       18 阅读

热门阅读

  1. Leetcode274. H 指数(简单易于理解)

    2024-06-17 08:58:05       7 阅读
  2. 跨服务器迁移 Redis 数据

    2024-06-17 08:58:05       6 阅读
  3. 《时间管理九段》前四阶段学习笔记

    2024-06-17 08:58:05       6 阅读
  4. LeetCode-day14-521. 最长特殊序列 Ⅰ

    2024-06-17 08:58:05       8 阅读
  5. leetcode67 二进制求和

    2024-06-17 08:58:05       8 阅读
  6. 力扣1631.最小体力消耗路径

    2024-06-17 08:58:05       7 阅读
  7. 算法第七天:leetcode之209.长度最小的子数组

    2024-06-17 08:58:05       6 阅读
  8. leetcode198 打家劫舍

    2024-06-17 08:58:05       8 阅读
  9. 结构型模式-享元模式

    2024-06-17 08:58:05       7 阅读
  10. CMake Tutorial (3.30-rc3版) 练习和点评

    2024-06-17 08:58:05       7 阅读
  11. HTML中的<br>、<hr>和<pre>标签使用指南

    2024-06-17 08:58:05       8 阅读
  12. 重庆思庄技术分享——启动Oracle下最小追踪日志

    2024-06-17 08:58:05       7 阅读
  13. vue实现图片预览

    2024-06-17 08:58:05       6 阅读
  14. 「C系列」C 文件读写

    2024-06-17 08:58:05       7 阅读
  15. 后端开发面试题4(附答案)

    2024-06-17 08:58:05       7 阅读
  16. C++ 二分查找法【面试】

    2024-06-17 08:58:05       6 阅读
  17. 1、C++编程中的基本运算 - 课件

    2024-06-17 08:58:05       7 阅读