c++多线程,mutex/recursive_mutex锁

mutex

void lock()

使用锁有三种情况,

1、任何线程都没有使用mutex, 则调用的线程使用mutex

2、有其他线程使用mutex,当前调用的线程会阻塞,直到其他使用锁的线程锁释放

3、如果mutex被同一线程调用,会产生死锁;

 

如果发生死锁, 会出现无定义行为,在某些特定库实现中,死锁会导致函数调用失败;

如果调用失败,会产生一个system_error

产生错误的条件有

errc::resource_deadlock_world_occur,errc::operation_not_permitted,orrc::device_or_resource_busy

检测到死锁,无权限,已经被锁

这些error也可以有其他情况;

bool try_lock()

如果当前没有线程使用mutex,则lock并返回true;

如果有其他线程使用mutex,try_lock函数会失败,返回false,并且不阻塞;

如果同一线程调用锁,产生死锁,try_lock函数返回值无定义(undefined behavior)

if (mutex.try_lock()) {
    //function op
    mutex.unlock();
`}

void unlock()

需要注意一点,如果一个锁并不属于当前调用线程,则会产生无定义行为;

 

recursive_mutex

constructor

constexpr recursive_mutex() noexception; //新建的object是没有mutex的

recursive_mutex(cosnt recursive_mutex&) = delete;  //不能拷贝或移动拷贝

构建过程不是原子的,所以在构建过程中会出现数据竞争;

void lock();

和mutex类似,如果没有线程使用,则上锁

如果有线程使用,则阻塞

如果同一线程使用mutex,则添加新一层mutex,对应的释放时,需要多一次unlock();

#include <iostream>
#include <thread>

using namespace std;

mutex mtx;

void PintCh(int n, char ch) {
    mtx.lock();
    for (int i = 0; i < n; ++i) {
        cout<<ch<<;
    }
    cout<<endl;
    mtx.unlock();
}

int main(void) {
    thread threads[10];
    for (int i = 0; i < 10; ++i) {
        threads[i] = thread(Printch, i + 1, '-');
    }
    for (auto& t : threads) {
        t.join();
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值