#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <windows.h>
using namespace std;
mutex mut;
condition_variable cond1, cond2;
int g_nums = 1;
void thread1() {
while (g_nums <= 100) {
unique_lock<mutex> locker(mut);
cout << "Thread1:" << g_nums << endl;
g_nums++;
cond2.notify_one();
cond1.wait(locker);
locker.unlock();
Sleep(1);
}
}
void thread2() {
while (g_nums <=100) {
Sleep(1);
unique_lock<mutex> locker(mut);
cout << "Thread2:" << g_nums << endl;
g_nums++;
cond1.notify_one();
cond2.wait(locker);
locker.unlock();
}
}
int main() {
thread t1(thread1);
thread t2(thread2);
t1.join();
t2.join();
system("pause");
return 0;
}
C++两个线程交替输出1~100(亲测可用)
最新推荐文章于 2024-06-05 23:18:59 发布