std::unique_lock 和 std::lock_guard

std::unique_lock 和 std::lock_guard

std::unique_lockstd::lock_guard 是 C++ 标准库中用于管理互斥锁的类模板,它们都提供了简化多线程编程中互斥访问的机制,但在功能和灵活性方面存在一些区别。

std::lock_guard:

std::lock_guard 是一个轻量级的互斥锁管理类,它通过构造函数获取锁,析构函数释放锁。std::lock_guard 对象一旦被创建,就会锁定互斥锁,一旦对象离开作用域,就会自动释放互斥锁,确保在任何情况下都不会忘记释放锁。因此,std::lock_guard 更适合简单的锁定范围,并且不能显式地释放锁。

下面是一个使用 std::lock_guard 的示例:

#include <iostream>
#include <mutex>

std::mutex mtx;  // Mutex for protecting the shared resource
int shared_data = 0;

void increment()
{
    std::lock_guard<std::mutex> lock(mtx);  // Acquire the lock on the mutex
    ++shared_data;  // Modify the shared resource
}  // Automatically release the lock upon leaving the scope

int main()
{
    std::cout << "Shared data before increment: " << shared_data << std::endl;
    increment();
    std::cout << "Shared data after increment: " << shared_data << std::endl;
    return 0;
}

std::unique_lock:

std::unique_lock 是一个更灵活和功能更强大的互斥锁管理类。它提供了更多的操作,如延迟加锁、手动释放锁、尝试加锁和超时加锁等。相比之下,std::unique_lock 具有更大的开销,因为它需要使用动态分配的资源来管理锁的状态。

下面是一个使用 std::unique_lock 的示例:

#include <iostream>
#include <mutex>

std::mutex mtx;  // Mutex for protecting the shared resource
int shared_data = 0;

void increment()
{
    std::unique_lock<std::mutex> lock(mtx);  // Acquire the lock on the mutex
    ++shared_data;  // Modify the shared resource
    lock.unlock();  // Release the lock
    // ... Do some other work without holding the lock
    lock.lock();  // Reacquire the lock
    // ... Do more work with the lock held
    lock.unlock();  // Release the lock
}

int main()
{
    std::cout << "Shared data before increment: " << shared_data << std::endl;
    increment();
    std::cout << "Shared data after increment: " << shared_data << std::endl;
    return 0;
}

在这个示例中,std::unique_lock 对象 lock 通过调用 lock() 方法获取锁,并通过 unlock() 方法手动释放锁。这样可以在不持有锁的情况下执行一些其他操作。之后,可以再次调用

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值