理发师问题的描述:一个理发店接待室有n张椅子,工作室有1张椅子;没有顾客时,理发师睡觉;第一个顾客来到时,必须将理发师唤醒;顾客来时如果还有空座的话,他就坐在一个座位上等待;如果顾客来时没有空座位了,他就离开,不理发了;当理发师处理完所有顾客,而又没有新顾客来时,他又开始睡觉。C语言实现
时间: 2024-03-17 20:45:14 浏览: 8
好的,以下是C语言实现。假设理发店接待室有5张椅子。
```c
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define N_SEATS 5 // 接待室座位数
#define WORK_CHAIR 1 // 理发师工作室椅子数
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_customers = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_barber = PTHREAD_COND_INITIALIZER;
int waiting_customers = 0;
int barber_sleeping = 0;
void *customer(void *arg);
void *barber(void *arg);
int main()
{
pthread_t barber_thread, customer_thread[20];
int i, id[20];
pthread_create(&barber_thread, NULL, barber, NULL);
for (i = 0; i < 20; i++) {
id[i] = i;
pthread_create(&customer_thread[i], NULL, customer, &id[i]);
sleep(1);
}
for (i = 0; i < 20; i++) {
pthread_join(customer_thread[i], NULL);
}
pthread_cancel(barber_thread);
pthread_join(barber_thread, NULL);
return 0;
}
void *customer(void *arg)
{
int id = *(int *)arg;
pthread_mutex_lock(&mutex);
printf("Customer %d comes.\n", id);
while (waiting_customers >= N_SEATS) {
printf("No seats available for customer %d. The customer leaves.\n", id);
pthread_mutex_unlock(&mutex);
return NULL;
}
waiting_customers++;
printf("Customer %d takes a seat. Waiting customers: %d.\n", id, waiting_customers);
pthread_cond_signal(&cond_customers); // 唤醒理发师
while (!barber_sleeping) {
printf("Customer %d is waiting for the barber.\n", id);
pthread_cond_wait(&cond_barber, &mutex); // 等待理发师完成理发
}
waiting_customers--;
barber_sleeping = 0;
printf("Customer %d is getting a haircut.\n", id);
pthread_mutex_unlock(&mutex);
return NULL;
}
void *barber(void *arg)
{
while (1) {
pthread_mutex_lock(&mutex);
while (waiting_customers == 0) {
printf("The barber is sleeping.\n");
barber_sleeping = 1;
pthread_cond_wait(&cond_customers, &mutex); // 等待顾客到来
}
printf("The barber starts to work. Waiting customers: %d.\n", waiting_customers);
waiting_customers--;
barber_sleeping = 0;
pthread_cond_signal(&cond_barber); // 唤醒顾客
pthread_mutex_unlock(&mutex);
sleep(3); // 理发师完成理发需要一定时间
}
}
```
上述代码中,使用了两个条件变量`cond_customers`和`cond_barber`,分别用于唤醒理发师和顾客。当顾客到来时,顾客线程调用`pthread_mutex_lock`锁定互斥量`mutex`,判断是否有空座位。如果没有,顾客离开;否则,顾客将等待理发师完成理发。当理发师完成理发后,顾客线程解锁互斥量`mutex`,跳出循环。当理发师睡眠时,理发师线程调用`pthread_cond_wait`等待条件变量`cond_customers`。当有顾客到来时,理发师被唤醒,理发师线程解锁互斥量`mutex`,跳出循环。然后理发师开始工作,完成后重新进入循环等待下一个顾客的到来。