我是 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);
}
}
}