两个线程交替打印奇数偶数
#include <thread>
#include <condition_variable>
#include <mutex>
#include <iostream>
using namespace std;
mutex mx;
condition_variable cv;
int number = 0;
void thread_func1()
{
unique_lock<mutex> lc(mx);
while (number <= 100)
{
while (number % 2 != 0)
{
cv.wait(lc);
}
if (number <= 100)
cout << number << " ";
number++;
cv.notify_all();
}
}
void thread_func2()
{
unique_lock<mutex> lc(mx);
while (number <= 100)
{
while (number % 2 != 1)
{
cv.wait(lc);
}
if (number <= 100)
cout << number << " ";
number++;
cv.notify_all();
}
}
int main()
{
thread s1(thread_func1);
thread s2(thread_func2);
s1.join();
s2.join();
system("pause");
return 0;
}
运行程序