Leetcode刷题笔记题解(C++):1114. 按序打印(多线程)

思路:

保证A,B,C三个线程的顺序不会变,即优先级顺序的问题

A,B需要资源1,B,C需要资源2

A先占用资源1和资源2,A线程完了之后释放资源1不释放资源2,然后B线程占用资源1,A线程完了之后释放资源1和资源2,这时候 C线程可以占用资源2并进行

cpp 复制代码
class Foo {
    //声明2个互斥量
    mutex mtx1,mtx2;
public:
    Foo() {
        //在类的构造函数中对2个互斥量进行加锁
        mtx1.lock();
        mtx2.lock();
    }

    void first(function<void()> printFirst) {
        //线程A的优先级较高,不需要去获取资源就可以进行
        // printFirst() outputs "first". Do not change or remove this line.
        printFirst();
        //线程A打印完之后对资源1进行释放,下一步线程B进行调用
        mtx1.unlock();
    }

    void second(function<void()> printSecond) {
        //去获取资源1,所有在A线程还没释放的时候B线程就不会进行下去
        mtx1.lock();
        // printSecond() outputs "second". Do not change or remove this line.
        printSecond();
        //对资源1进行释放
        mtx1.unlock();
        //对资源2进行释放,下一步线程C进行调用
        mtx2.unlock();
    }

    void third(function<void()> printThird) {
        //去获取资源2,所有在B线程还没释放的时候C   线程就不会进行下去
        mtx2.lock();
        // printThird() outputs "third". Do not change or remove this line.
        printThird();
        //对资源2进行释放
        mtx2.unlock();
    }
};
相关推荐
CN-Dust5 小时前
【C++】while语句例题专题
数据结构·c++·算法
用户805533698035 小时前
现代Qt开发教程(新手篇)1.11——定时器
c++·qt
澈2075 小时前
STL迭代器:容器遍历的万能钥匙
开发语言·c++
azoo5 小时前
emplace_back和push_back() 函数添加 cv::Point 类型数据
c++·opencv
freexyn6 小时前
Matlab自学笔记七十六:表达式的展开、因式分解、化简、合并同类项
笔记·算法·matlab
样例过了就是过了6 小时前
LeetCode热题 不同路径
c++·算法·leetcode·动态规划
Navigator_Z7 小时前
LeetCode //C - 1031. Maximum Sum of Two Non-Overlapping Subarrays
c语言·算法·leetcode
橙子也要努力变强7 小时前
信号的保存、阻塞与递达
linux·服务器·c++
旖-旎8 小时前
深搜练习(组合总和)(7)
c++·算法·深度优先·力扣