C++实现两个线程交替打印奇偶数
Posted _BitterSweet
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++实现两个线程交替打印奇偶数相关的知识,希望对你有一定的参考价值。
#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;
//线程1
void thread1()
{
while (1)
{
unique_lock<mutex> locker(mut);
cout << "Thread1:" << g_nums << endl;
g_nums++;
cond2.notify_one();
cond1.wait(locker);
locker.unlock();
Sleep(1000);
}
}
//线程2
void thread2()
{
while (1)
{
Sleep(1000);
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++实现两个线程交替打印奇偶数的主要内容,如果未能解决你的问题,请参考以下文章