linx下使用线程模拟解决银行排队叫号问题。 在银行中有一个叫号机,有一个10个座位的长椅,客户在叫号后如果无人在柜台前服务,就会去要求服务;如果柜台忙,则会找长椅入座;如果长椅满则会离开。 要求显示输出叫号过程,并分析程序运行状况。
时间: 2023-12-29 18:03:12 浏览: 24
以下是一个使用线程模拟解决银行排队叫号问题的示例代码:
```c++
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <chrono>
using namespace std;
queue<int> q;
mutex mtx;
condition_variable cv;
int ticket = 0;
bool running = true;
void customer() {
unique_lock<mutex> lck(mtx);
int my_ticket = ++ticket;
cout << "Customer " << my_ticket << " gets a ticket." << endl;
q.push(my_ticket);
cv.notify_all();
}
void teller() {
while (running) {
unique_lock<mutex> lck(mtx);
while (q.empty()) {
cv.wait(lck);
}
int customer = q.front();
q.pop();
cout << "Teller is serving customer " << customer << "." << endl;
lck.unlock();
this_thread::sleep_for(chrono::seconds(3));
cout << "Teller has finished serving customer " << customer << "." << endl;
}
}
int main() {
thread t(teller);
for (int i = 0; i < 15; ++i) {
customer();
this_thread::sleep_for(chrono::seconds(1));
}
running = false;
cv.notify_all();
t.join();
return 0;
}
```
在这个示例中,有两个线程:一个是叫号机(customer),另一个是柜台(teller)。叫号机不断生成新的客户,每个客户都会得到一个唯一的号码,并加入等待队列中。柜台不断从等待队列中取出客户进行服务,如果队列为空,就等待叫号机的通知。每个客户在柜台前等待3秒钟后,服务结束,柜台可以服务下一个客户。
在主函数中,我们生成15个客户,然后设定running标志为false,通知柜台线程结束。最后,等待柜台线程结束后,程序结束。
运行程序,会看到类似以下的输出:
```
Customer 1 gets a ticket.
Teller is serving customer 1.
Customer 2 gets a ticket.
Customer 3 gets a ticket.
Customer 4 gets a ticket.
Teller has finished serving customer 1.
Customer 5 gets a ticket.
Teller is serving customer 2.
Customer 6 gets a ticket.
Teller has finished serving customer 2.
Customer 7 gets a ticket.
Teller is serving customer 3.
Customer 8 gets a ticket.
Teller has finished serving customer 3.
Customer 9 gets a ticket.
Teller is serving customer 4.
Customer 10 gets a ticket.
Teller has finished serving customer 4.
Customer 11 gets a ticket.
Teller is serving customer 5.
Customer 12 gets a ticket.
Teller has finished serving customer 5.
Customer 13 gets a ticket.
Teller is serving customer 6.
Customer 14 gets a ticket.
Teller has finished serving customer 6.
Customer 15 gets a ticket.
Teller is serving customer 7.
Teller has finished serving customer 7.
Teller is serving customer 8.
Teller has finished serving customer 8.
Teller is serving customer 9.
Teller has finished serving customer 9.
Teller is serving customer 10.
Teller has finished serving customer 10.
Teller is serving customer 11.
Teller has finished serving customer 11.
Teller is serving customer 12.
Teller has finished serving customer 12.
Teller is serving customer 13.
Teller has finished serving customer 13.
Teller is serving customer 14.
Teller has finished serving customer 14.
Teller is serving customer 15.
Teller has finished serving customer 15.
```
可以看到,客户依次得到了号码,并排队等待服务。柜台逐一服务每个客户,直到所有客户都得到了服务。