请给出一段解决理发师问题的c++多线程代码
以下是使用C++多线程解决理发师问题的示例代码:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex mtx;
condition_variable cv;
bool ready = false;
int customerCount = 0;
int hairCutCount = 0;
int maxHairCutCount = 10;
void barber() {
while (hairCutCount < maxHairCutCount) {
unique_lock<mutex> lck(mtx);
while (!ready) {
cv.wait(lck);
}
customerCount--;
cout << "Barber is cutting hair." << endl;
hairCutCount++;
ready = false;
lck.unlock();
cv.notify_all();
}
}
void customer() {
while (hairCutCount < maxHairCutCount) {
unique_lock<mutex> lck(mtx);
while (customerCount >= 1) {
cv.wait(lck);
}
customerCount++;
cout << "Customer is waiting for a hair cut." << endl;
ready = true;
lck.unlock();
cv.notify_all();
}
}
int main() {
thread b(barber);
thread c1(customer);
thread c2(customer);
thread c3(customer);
thread c4(customer);
thread c5(customer);
b.join();
c1.join();
c2.join();
c3.join();
c4.join();
c5.join();
cout << "All customers have received hair cuts." << endl;
return 0;
}
在上面的代码中,我们使用mutex和condition_variable来实现同步和互斥。mutex用于保护共享变量,condition_variable用于在线程之间传递信号。
在barber函数中,理发师会在循环中等待ready变量为true,表示有顾客需要理发。一旦有顾客需要理发,理发师会减少customerCount,然后进行理发,并将ready设置为false表示理发师现在可以等待下一个顾客。
在customer函数中,顾客会在循环中等待customerCount为0,表示没有顾客需要理发。一旦没有顾客需要理发,顾客会增加customerCount,并将ready设置为true表示顾客现在可以等待理发师。
在主函数中,我们启动了一个理发师线程和五个顾客线程。理发师将一直工作直到hairCutCount达到maxHairCutCount。一旦所有顾客都接受了理发,我们输出一条消息表示程序已经完成。
这是一个简单的解决理发师问题的多线程实现,但是它可以扩展到更复杂的情况下
原文地址: https://www.cveoy.top/t/topic/ffm2 著作权归作者所有。请勿转载和采集!