多线程Leetcode1114.按序印

 

其实我写的不通过,使用了unique_lock创建独占锁,发现执行不通过,于是参考了别人的正确答案:

我的错误答案:

class Foo {
public:
    Foo() {
        std::mutex lmutex;
         thread threadFirst(&first);
         thread threadSecond(&second);
         thread threadThird(&third);
         threadFirst.join();
         threadSecond.join();  
    }

    void first(function<void()> printFirst) {
        unique_lock<mutex> lock(lmutex);
        // printFirst() outputs "first". Do not change or remove this line.
        printFirst();
    }

    void second(function<void()> printSecond) {
         unique_lock<mutex> lock(lmutex);
        // printSecond() outputs "second". Do not change or remove this line.
        printSecond();
    }

    void third(function<void()> printThird) {
         unique_lock<mutex> lock(lmutex);
        // printThird() outputs "third". Do not change or remove this line.
        printThird();
    }
};

别人的正确答案:

Use mutex

std::mutex和std::condition_variable这两个库用于互斥锁的实现.

std::mutex 的介绍:

一. 构造函数,std::mutex不允许拷贝构造,,也不允许move拷贝,最初产生的mutex对象是处于unlocked状态的.

二. lock(),调用线程将锁住该互斥量。线程调用该函数会发生下面 3 种情况:

(1)如果该互斥量当前没有被锁住,则调用线程将该互斥两锁住,直到调用unlock之前,该线程一直拥有该锁.

(2)如果当前互斥量被其他线程锁住,则当前的调用线程被阻塞住。

(3)如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。

三. unlock(), 解锁,释放对互斥量的所有权。

四. try_lock(),尝试锁住互斥量,如果互斥量被其他线程占有,则当前线程也不会被阻塞。线程调用该函数也会出现下面 3 种情况,(1). 如果当前互斥量没有被其他线程占有,则该线程锁住互斥量,直到该线程调用 unlock 释放互斥量。(2). 如果当前互斥量被其他线程锁住,则当前调用线程返回 false,而并不会被阻塞掉。(3). 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。

五.互斥量被锁住的时候,线程执行lock()函数是会被阻塞的,只有在互斥量被unlock()之后,lock()函数才会被执行。所以可以通过设置两个互斥锁分别对second和third进行锁定。

class Foo {
public:
    Foo() {
        smx.lock();
        tmx.lock();
    }
    void first(function<void()> printFirst) {
        
        // printFirst() outputs "first". Do not change or remove this line.
        printFirst();
        smx.unlock();
    }

    void second(function<void()> printSecond) {
        smx.lock();
        // printSecond() outputs "second". Do not change or remove this line.
        printSecond();
        tmx.unlock();
    }

    void third(function<void()> printThird) {
        tmx.lock();
        // printThird() outputs "third". Do not change or remove this line.
        printThird();
    }
private:
  mutex smx,tmx;
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值