c++实现理发师问题。。
时间: 2023-08-07 18:22:20 浏览: 42
理发师问题是一个经典问题,也称为“睡眠理发师问题”。在这个问题中,有一个理发店和一位理发师。理发店有 n 把椅子,每把椅子可以坐一个人。如果顾客来了,他们会坐在一张椅子上等待理发师为他们理发。如果没有空椅子,顾客会离开。当理发师空闲时,他会叫下一个顾客过来理发。如果没有顾客等待,理发师会睡觉直到有顾客到来为止。
下面是一个简单的 C++ 实现:
```cpp
#include <iostream>
#include <queue>
#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>
using namespace std;
const int n = 5; // 椅子数
queue<int> waitingCustomers; // 等待理发的顾客队列
mutex mtx; // 互斥锁
condition_variable cv; // 条件变量
bool sleeping = true; // 理发师是否在睡觉
// 顾客线程函数
void customer(int id) {
unique_lock<mutex> lck(mtx);
cout << "顾客 " << id << " 进入理发店" << endl;
if (waitingCustomers.size() < n) {
waitingCustomers.push(id);
cout << "顾客 " << id << " 等待理发" << endl;
cv.notify_all();
} else {
cout << "顾客 " << id << " 离开理发店" << endl;
}
}
// 理发师线程函数
void barber() {
unique_lock<mutex> lck(mtx);
while (true) {
// 如果没有等待理发的顾客,理发师睡觉
if (waitingCustomers.empty()) {
cout << "理发师睡觉" << endl;
sleeping = true;
cv.wait(lck);
}
// 理发师叫下一个顾客过来理发
int id = waitingCustomers.front();
waitingCustomers.pop();
cout << "理发师为顾客 " << id << " 理发" << endl;
sleeping = false;
// 理发时间
this_thread::sleep_for(chrono::seconds(1));
}
}
int main() {
thread barberThread(barber);
for (int i = 1; i <= 10; i++) {
thread customerThread(customer, i);
this_thread::sleep_for(chrono::milliseconds(200));
customerThread.detach();
}
barberThread.join();
return 0;
}
```
在这个实现中,顾客和理发师都是线程函数。当顾客来到理发店时,它会尝试坐在一把椅子上等待理发。如果没有空椅子,顾客会离开。当理发师空闲时,它会叫下一个顾客过来理发。如果没有顾客等待,理发师会睡觉直到有顾客到来为止。这个实现使用了 STL 中的队列、互斥锁和条件变量来完成同步和互斥操作。