linux C++互斥锁std::lock_guard(轻锁)std::unique_lock(重锁)区别、使用{}来控制轻锁lock_guard的生命周期(lock_guard不支持手动解锁)

448 篇文章 27 订阅

lock_guard和unique_lock区别

lock_guard 和 unique_lock 都是 C++ 标准库提供的互斥锁 RAII 封装工具,用于实现互斥访问,但它们有一些不同之处:

lock_guard 是基于互斥锁 std::mutex 实现的,unique_lock 是基于通用锁 std::unique_lock 实现的,unique_lock 可以实现比 lock_guard 更灵活的锁操作。
lock_guard 是不可移动的(moveable),即不能拷贝、赋值、移动,只能通过构造函数初始化和析构函数销毁,unique_lock 是可移动的,可以拷贝、赋值、移动。
unique_lock 提供了更多的控制锁的行为,比如锁超时、不锁定、条件变量等。
unique_lock 比 lock_guard 更重,因为它有更多的功能,更多的开销。如果只需要简单的互斥保护,使用 lock_guard 更好。

另外,unique_lock 支持手动解锁,而 lock_guard 不支持。

下面是 lock_guard 和 unique_lock 的简单使用示例,可以看出二者在使用方法上的区别

#include <iostream>
#include <mutex>
#include <thread>

std::mutex m;

void worker()
{
    std::lock_guard<std::mutex> lg(m);  // lock_guard 方式上锁
    std::cout << "worker thread is running..." << std::endl;
    // 这里可以写一些需要互斥保护的代码
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "worker thread is done." << std::endl;
}  // lock_guard 不支持手动解锁,会在此自动释放锁

void another_worker()
{
    std::unique_lock<std::mutex> ul(m);  // unique_lock 方式上锁
    std::cout << "another worker thread is running..." << std::endl;
    // 这里可以写一些需要互斥保护的代码
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "another worker thread is done." << std::endl;
    ul.unlock();  // 手动释放锁
    //do something...
}  // 如果锁未释放,unique_lock 会在此自动释放锁

int main()
{
    std::thread t1(worker);
    std::thread t2(another_worker);
    t1.join();
    t2.join();
    return 0;
}

编译运行结果:

g++ test.cpp -lpthread && ./a.out 

在这里插入图片描述

示例:用std::lock_guard加互斥锁

std::lock_guard 是 C++11 中的标准库,是一个实现互斥锁的简单模板类。
它的使用方法很简单,只需要在代码中创建一个 std::lock_guard 对象,并传入一个互斥锁,在它的生命周期内,互斥锁的访问权限将被控制。

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <vector>

std::mutex mtx;
std::vector<int> data;

void func1()
{
    std::lock_guard<std::mutex> lock(mtx); // 创建 lock_guard 对象
    for (int i = 0; i < 10; ++i)
    {
        data.push_back(i); 
        std::cout << "func1: " << i << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

void func2()
{
    std::lock_guard<std::mutex> lock(mtx); // 创建 lock_guard 对象
    for (int i = 100; i < 110; ++i)
    {
        data.push_back(i);
        std::cout << "func2: " << i << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

int main()
{
    std::thread thrd1(func1);
    std::thread thrd2(func2);

    thrd1.join();
    thrd2.join();

    for (auto &i : data)
    {
        std::cout << i << " ";
    }
    std::cout << std::endl;
    return 0;
}

编译运行:

g++ test.cpp -lpthread && ./a.out

在这里插入图片描述

示例:用std::unique_lock加互斥锁并手动释放锁

在 C++ 中,互斥锁通常是通过 RAII 机制来保证自动释放,即在锁对象的生命周期结束时自动释放锁。但是,在某些情况下,可能需要手动释放互斥锁。在 C++11 中,可以通过 std::unique_lock::unlock() 方法来手动释放互斥锁。

下面是一个简单的示例代码,演示了如何手动释放互斥锁:

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>

std::mutex g_mutex;
int count = 0;

void func()
{
    std::unique_lock<std::mutex> lock(g_mutex);
    std::cout << "Thread " << std::this_thread::get_id() << " acquired the lock." << std::endl;
    count++;
    std::cout << "Thread " << std::this_thread::get_id() << " count = " << count << std::endl;
    lock.unlock(); // 手动释放互斥锁  //如果不手动释放,锁会在函数结束时自动释放
    std::cout << "Thread " << std::this_thread::get_id() << " released the lock." << std::endl;
    //do somethine...
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main()
{
    const int numThreads = 1000;

    std::thread threads[numThreads];
    for (int i = 0; i < numThreads; ++i) {
        threads[i] = std::thread(func);
    }

    for (int i = 0; i < numThreads; ++i) {
        threads[i].join();
    }

    std::cout << "final count = " << count << std::endl;

    return 0;
}

编译运行结果:

g++ test.cpp -lpthread && ./a.out

在这里插入图片描述

使用{}来控制轻锁lock_guard的生命周期

当使用{}括起来的代码块创建std::lock_guard对象时,std::lock_guard的生命周期将仅限于该代码块内部。

std::lock_guard是一个在构造函数中获取互斥锁,在析构函数中释放互斥锁的RAII类。当std::lock_guard对象的生命周期结束时,它会自动释放所持有的互斥锁,以避免出现死锁和其他相关的问题。

当您在代码块中创建std::lock_guard对象时,它的析构函数将在代码块结束时自动调用,从而释放锁。这意味着锁的作用范围将仅限于该代码块内部,并且在代码块外部无法访问该锁。

下面是一个示例代码,演示了如何在代码块内使用std::lock_guard对象:

#include <mutex>

std::mutex m; // 互斥锁

void foo()
{
    {
        std::lock_guard<std::mutex> guard(m); // 创建 std::lock_guard 对象
        // 在这个代码块中,互斥锁 m 被锁定
        // 执行一些需要互斥访问的代码
    } // std::lock_guard 对象在这里销毁,互斥锁 m 被解锁
    // 在这个代码块外,无法访问锁 m
}

完整测试代码:

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>

std::mutex m; // 互斥锁
int shared_data = 0; // 共享数据

void worker(int id)
{
    // 在循环中修改共享数据
    for (int i = 0; i < 5; ++i) 
    {
        {
            std::lock_guard<std::mutex> guard(m); // 创建 std::lock_guard 对象
            shared_data++; // 修改共享数据
            std::cout << "Worker " << id << " modified shared data to " << shared_data << std::endl;
        } //销毁lock_guard,释放锁
        printf("Worker %d relead lock.......................................\n", id);
        std::this_thread::sleep_for(std::chrono::seconds(1));
        printf("Worker %d has sleep 1 second.......................................\n", id);
    } // std::lock_guard 对象在这里销毁,互斥锁 m 被解锁
}

int main()
{
    std::thread t1(worker, 1);
    std::thread t2(worker, 2);

    t1.join();
    t2.join();

    std::cout << "Final value of shared data is " << shared_data << std::endl;

    return 0;
}

在上面的示例代码中,有两个线程t1和t2,它们同时访问共享数据shared_data。为了避免数据竞争和其他并发问题,我们使用了std::mutex和std::lock_guard来确保只有一个线程可以访问共享数据。

在worker()函数中,我们使用了std::lock_guard对象guard来锁定互斥锁m,以确保每个线程在修改共享数据时都能够获得锁。当std::lock_guard对象在代码块末尾销毁时,互斥锁将自动解锁,从而允许其他线程访问共享数据。

在main()函数中,我们创建了两个线程t1和t2,它们分别执行worker()函数。我们使用t1.join()和t2.join()等待线程执行完毕,然后输出最终的共享数据值。

编译运行结果:

在这里插入图片描述

  • 13
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Dontla

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

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

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

打赏作者

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

抵扣说明:

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

余额充值