实现两个线程交叠输出1-n

发布时间 2023-09-05 15:26:29作者: SuperTonyy
#include <bits/stdc++.h>
#include <mutex>
#include <windows.h>

using namespace std;
mutex m; //定义互斥信号量
condition_variable cond1, cond2;
int cur = 1; //定义当前打印到哪个数字了

void thread1() {
    while (cur <= 100) {
        unique_lock<mutex> lock(m);
        cout << "线程1打印" << cur++ << endl;
        cond2.notify_one(); //通知等待的线程2
        cond1.wait(lock); //线程1进入等待
        lock.unlock();
        Sleep(1);
    }
}

void thread2() {
    while (cur <= 100) {
        unique_lock<mutex> lock(m);
        cout << "线程2打印" << cur++ << endl;
        cond1.notify_one(); //唤醒线程1
        cond2.wait(lock); //线程2进入等待
        lock.unlock();
        Sleep(1);
    }
}

int main()
{
    thread t1(thread1);
    thread t2(thread2);
    t1.join();
    t2.join();
    return 0;
}