我正在尝试实施睡眠理发师问题的解决方案。我为理发师编写了以下代码:
while(1){
sem_wait(semsid, mutex);
if(semctl(semsid, customer, GETVAL, 0) == 0){
logg("...zzz...zzz...\n");
}
sem_signal(semsid, mutex);
sem_wait(semsid, customer);
sem_wait(semsid, isSomeoneCut_sem);
FIFO->isSomeoneCut = 1;
sem_signal(semsid, isSomeoneCut_sem);
sem_wait(semsid, mutex); //blokujemy dostęp do kolejki
int* tmp = qpop(FIFO, addrFifo);
int pid = tmp[0];
int sem = tmp[1];
FIFO->customers--;
sem_signal(semsid, sem);
sem_signal(semsid, mutex); //.odbblokowujemy kolejkę
cutHair(pid);
sem_wait(semsid, customerDone); //razem kończymy strzyżenie
sem_signal(semsid, barberDone);
sem_wait(semsid, isSomeoneCut_sem);
FIFO->isSomeoneCut = 0;
sem_signal(semsid, isSomeoneCut_sem);
}
以下为客户:
sem_wait(semsid, mutex);
sem_wait(semsid, isSomeoneCut_sem);
if(qisFull(q)){ //queue is full, leaving
logg("queue is FULL, leaving.\n");
sem_signal(semsid, isSomeoneCut_sem);
sem_signal(semsid, mutex);
sleep(1);
continue;
}
else if(qisEmpty(q) && q->isSomeoneCut == 0){
logg("Nobody's waiting, waking the barber.\n");
}
else{
q->customers++;
logg("Taking a seat in waiting room.\n");
}
sem_signal(semsid, isSomeoneCut_sem);
int mysem = getSemInd(q);
semctl(semsid, mysem, SETVAL, 0);
qpush(q, addrFifo, getpid(), mysem);
sem_signal(semsid, mutex);
sem_signal(semsid, customer);
sem_wait(semsid, mysem);
getHaircut();
sem_signal(semsid, customerDone); //wspólnie kończymy strzyżenie
sem_wait(semsid, barberDone);
logg("I was cut and am leaving the shop.\n");
FIFO与标志,队列中的客户数量等一起保存在共享内存段中。当我运行程序时,我遇到了一个小问题: - 理发师不能立即设置标志是在醒来后的某人切断(有人可以打断他,例如再次唤醒他。 如果您发现任何其他问题,请告诉我。 提前谢谢!