c++11常用的锁用法

这里只介绍std::lock_guard、std::unique_lock

  • std::unique_lock被称为唯一锁或独占锁。与std::lock_guard相比,std::unique_lock允许在锁的生命周期内手动控制锁的锁定和解锁,而不仅仅是在构造函数和析构函数中自动进行。这使得std::unique_lock在更复杂的场景中更加有用,例如当需要在锁的持有期间进行条件变量等待时。
  • std::lock_guard 通常被称为 锁定守卫(Lock Guard)或 范围锁(Scoped
    Lock)。它的主要目的是确保在特定代码块(作用域)内,某个互斥量(mutex)总是被锁定,并在离开该作用域时自动解锁。这样可以防止由于忘记解锁而导致的线程安全问题。

std::lock_guard 示例
代码解读:当奇数的时候,抛出异常。锁自动解除(因为离开了作用域)

#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::lock_guard
#include <stdexcept>      // std::logic_error
 
std::mutex mtx;
 
void print_even (int x) {
    if (x%2==0) std::cout << x << " is even\n";
    else throw (std::logic_error("not even"));
}
 
void print_thread_id (int id) {
    try {
        // using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:
        std::lock_guard<std::mutex> lck (mtx);
        print_even(id);
    }
    catch (std::logic_error&) {
        std::cout << "[exception caught]\n";
    }
}
 
int main ()
{
    std::thread threads[10];
    // spawn 10 threads:
    for (int i=0; i<10; ++i)
        threads[i] = std::thread(print_thread_id,i+1);
 
    for (auto& th : threads) th.join();
 
    return 0;
}

std::unique_lock 示例
代码解读:要么先打印50个*然后打印50个 。要么反之。总之保证 ∗ 和 。要么反之。总之保证*和 。要么反之。总之保证的打印是连续的

#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::unique_lock
 
std::mutex mtx;           // mutex for critical section
 
void print_block (int n, char c) {
    // critical section (exclusive access to std::cout signaled by lifetime of lck):
    std::unique_lock<std::mutex> lck (mtx);
    for (int i=0; i<n; ++i) {
        std::cout << c;
    }
    std::cout << '\n';
}
 
int main ()
{
    std::thread th1 (print_block,50,'*');
    std::thread th2 (print_block,50,'$');
 
    th1.join();
    th2.join();
 
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值