c++实现理发师问题,要求有多个理发师
时间: 2024-02-27 10:52:49 浏览: 18
理发师问题是一个经典的并发编程问题,可以使用多线程来实现。以下是一个C++实现的示例:
```cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
using namespace std;
mutex mtx; // 互斥锁,用于保护共享资源
condition_variable cv; // 条件变量,用于线程间的同步
queue<int> q; // 等待理发的顾客队列
// 理发师线程函数
void barber(int id) {
while (true) {
unique_lock<mutex> lock(mtx);
// 等待有顾客
cv.wait(lock, []{ return !q.empty(); });
// 取出队首顾客
int customer = q.front();
q.pop();
lock.unlock();
cv.notify_all();
// 理发
cout << "barber " << id << " is cutting hair for customer " << customer << endl;
// 模拟理发的时间
this_thread::sleep_for(chrono::milliseconds(200));
}
}
// 顾客线程函数
void customer(int id) {
unique_lock<mutex> lock(mtx);
// 如果没有空闲的理发师,则等待
cv.wait(lock, []{ return q.size() < 5; });
// 进入等待队列
q.push(id);
lock.unlock();
cv.notify_all();
// 等待理发
cv.wait(lock, [id]{ return id == q.front(); });
lock.unlock();
// 理发完成,离开
cout << "customer " << id << " is leaving" << endl;
}
int main() {
thread b1(barber, 1);
thread b2(barber, 2);
thread b3(barber, 3);
thread c1(customer, 1);
thread c2(customer, 2);
thread c3(customer, 3);
thread c4(customer, 4);
thread c5(customer, 5);
b1.join();
b2.join();
b3.join();
c1.join();
c2.join();
c3.join();
c4.join();
c5.join();
return 0;
}
```
以上代码实现了三个理发师和五个顾客的场景。理发师使用无限循环等待顾客,当有顾客到来时,从等待队列中取出一个顾客并进行理发。顾客线程首先等待有空闲的理发师,然后进入等待队列,等待理发师的服务。理发完成后,顾客离开。在实现中,使用互斥锁保护共享资源,使用条件变量进行线程间的同步。