我是OpenMP的新手,出于学习目的,我正在尝试实施睡眠理发师问题。但是我无法按照我的意愿运行代码。
这就是我希望代码运行的方式:
Creating customer 0
Creating customer 1
Creating customer 2
Creating customer 3
Creating customer 4
Sleeping
Customer: 3 waiting for seats
Customer: 3 ready, waiting for barber
Customer: 1 waiting for seats
Customer: 1 ready, waiting for barber
Customer: 2 waiting for seats
Customer: 2 ready, waiting for barber
Customer: 4 waiting for seats
Customer: 4 ready, waiting for barber
Customer: 0 waiting for seats
Customer: 0 ready, waiting for barber
Barber: waiting for customer
Barber: waiting for seats
Customer: 2 is done. Leaving..
Number of customers hair cutted: 1
Barber: waiting for customer
Barber: waiting for seats
Customer: 1 is done. Leaving..
然而这就是它实际运行的方式:
Creating customer 0
Creating customer 1
Creating customer 2
Creating customer 3
Creating customer 4
Customer: 0 waiting for seats
Customer: 0 ready, waiting for barber
Barber: waiting for customer
Barber: waiting for seats
Customer: 0 is done. Leaving..
Customer: 1 waiting for seats
Customer: 1 ready, waiting for barber
Number of customers hair cutted: 1
Barber: waiting for customer
Barber: waiting for seats
Customer: 1 is done. Leaving..
Customer: 2 waiting for seats
Customer: 2 ready, waiting for barber
Number of customers hair cutted: 2
Barber: waiting for customer
etc..
正如您所看到的,它只是一次只有一个客户,正在等待信号量,他们不知何故等待其他客户任务完成。
代码:
void customer(int threadid)
{
int hairCutted = 0;
while (!hairCutted) {
printf("Customer: %ld waiting for seats\n", (long)threadid);
sem_wait(&accessWRSeats);
if (numOfFreeSeats >0) {
numOfFreeSeats--;
sem_post(&custReady);
sem_post(&accessWRSeats);
printf("Customer: %ld ready, waiting for barber\n", (long)threadid);
sem_wait(&barberReady);
hairCutted = 1;
}
else {
sem_post(&accessWRSeats);
hairCutted = 1;
}
}
printf("Customer: %ld is done. Leaving..\n", (long)threadid);
}
void createCustomers(void)
{
int i;
printf("Random number: %d\n", randNum1);
#pragma omp parallel
{
#pragma omp single firstprivate(i)
for (i = 0; i < randNum1; ++i)
{
#pragma omp task
customer(i);
printf("Creating customer %d\n", i);
}
}
printf("Sleeping\n");
sleep(60);
int j;
printf("Random number: %d\n", randNum2);
#pragma omp parallel
{
#pragma omp single firstprivate(i)
for (j = 0; j < randNum2; ++j, ++i)
{
#pragma omp task
customer(i);
printf("Creating customer %d\n", i);
}
}
}
答案 0 :(得分:0)
看一下这段代码:
sem_wait(&accessWRSeats);
if (numOfFreeSeats >0)
{
...
}
else
{
sem_post(&accessWRSeats);
hairCutted = 1;
}
如果客户没有免费座位,客户为什么会理发? (这意味着理发店已满,因此,理发师正在忙着参加其他一些客户。)
他应该发出信号accessWRSeats
,离开并再试一次......