#include<iostream>
#include<thread>
#include<vector>
#include<conio.h>
#include<atomic>
#include<mutex>
using namespace std;
class Test {
public:
void producer();
void consumer();
void wait(atomic_llong &s, mutex &t);
void signal(atomic_llong &s);
int t;
private:
thread *pd, *cs;
mutex mymutex,fm,em; //fm避免多个消费者同时操作fill,em->empty(信号量也是临界资源)
atomic_llong fill = 0, empty = 5;
};
void Test::wait(atomic_llong &s, mutex &t) {
t.lock();
while (s <= 0);
s -= 1;
t.unlock();
}
void Test::signal(atomic_llong &s) {
s += 1;
}
void Test::consumer() {
cs = new thread([this]() {
wait(fill,fm);
mymutex.lock();
cout << "已成功撤离——" << "当前人数:" << fill << endl << endl;
mymutex.unlock();
signal(empty);
});
cs->detach();
}
void Test::producer() {
pd = new thread([this]() {
wait(empty,em);
mymutex.lock();
cout << "部队已到达——" << "当前人数:" << fill + 1 << endl << endl;
mymutex.unlock();
signal(fill);
});
pd->detach();
}
int main() {
Test t;
char ch; //使用按键 a 进行生产,按键 s 进行消费
cout << "使用按键 a 呼叫支援,按键 s 撤退" << endl;
while (true) {
if (_kbhit()) { //非阻塞函数:检测是否有键盘输入
ch = _getch(); //不回显输入函数
if (ch == 'a') {
cout << "呼叫总部,呼叫总部,请求空中支援" << endl;
t.producer();
}
else if (ch == 's') {
cout << "呼叫总部,呼叫总部,请求撤离" << endl;
t.consumer();
}
}
}
system("pause");
return 0;
}