环境: windows + vs2015
参考:
https://blog.csdn.net/qq_44875284/article/details/123876085
直接上代码:
#include <Windows.h>
#include <thread>
#include <mutex>
#include <atomic>
#include <iostream>
#include <condition_variable>
using namespace std;
std::mutex mtx;
std::condition_variable cond;
void func1(int& apple)
{
while (1)
{
{
std::unique_lock<std::mutex> lck(mtx);
apple += 1;
cond.notify_one();//唤醒一个等待的线程
}
Sleep(1000);
}
}
void func2(int& apple)
{
while (1)
{
std::unique_lock<std::mutex> lck(mtx);
if (apple) {
std::cout << apple << '\n';
apple -= 1;
continue;
}
cond.wait(lck);//等待线程
}
}
int main()
{
int apple = 0;
std::thread t1(func1, std::ref(apple));
std::thread t2(func2, std::ref(apple));
t2.join();
t1.join();
cin.get();
return 0;
}
记录完成