Leetcode刷题笔记题解(C++):1116. 打印零与奇偶数(多线程)

Leetcode刷题笔记题解(C++):1116. 打印零与奇偶数(多线程)_第1张图片

思路:

互斥锁+条件判断奇偶

class ZeroEvenOdd {
private:
    int n;
    //定义三个线程的互斥量
    mutex mtx1,mtx2,mtx3;
public:
    ZeroEvenOdd(int n) {
        this->n = n;
        //对0线程解资源
        mtx1.unlock();
        mtx2.lock();
        mtx3.lock();
    }

    // printNumber(x) outputs "x", where x is an integer.
    void zero(function printNumber) {
        for(int i = 1;i<=n;i++){
            mtx1.lock();
            printNumber(0);
            //如果当前为偶数则释放偶线程的资源锁
            if(i%2 == 0) mtx2.unlock();
            //如果当前为奇数则释放奇线程的资源锁
            else mtx3.unlock();
        }
    }

    void even(function printNumber) {
        for(int i = 2;i<=n;i+=2){
            mtx2.lock();
            printNumber(i);
            //释放0线程的资源锁
            mtx1.unlock();
        }
    }

    void odd(function printNumber) {
        for(int i = 1;i<=n;i+=2){
            mtx3.lock();
            printNumber(i);
            //释放0线程的资源锁
            mtx1.unlock();
        }
    }
};

你可能感兴趣的:(Leetcode算法题解,leetcode,笔记,c++)