【发布时间】:2019-03-08 03:03:48
【问题描述】:
问题:
此代码用于解决同步问题,称为寿司吧问题。规则如下:
想象一下有 5 个座位的寿司吧。如果您在有 空座,可以马上坐下。但是,如果您在所有座位时到达 吃饱了,说明大家一起吃饭,你会 坐下之前必须等待整个聚会都离开。
脚本:
这里的代码使用信号量在 C 中工作。我一直试图在没有信号量的情况下编写它,但无济于事。它不必是 C 语言,它可以是 C++ 或其他语言。
我在考虑条件变量,但我不确定如何实现它们。如果有人可以帮忙,我将不胜感激!
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdbool.h>
int eating = 0, waiting = 0;
bool must_wait = false;
sem_t block;
sem_t mutex;
void * sushiBar(void * threadID)
{
usleep(rand() % 1000);
sem_wait(&mutex);
if(must_wait){
printf("Waits: %d seats are available. %d other people waiting.\n", 5-eating, waiting);
waiting++;
sem_post(&mutex);
sem_wait(&block);
waiting--;
}
if(eating == 4)
printf("Last seat is taken.\n");
else{
printf("%d seats available. Sits and eats sushi.\n", 5-eating);
}
eating++;
must_wait = (eating == 5);
if(waiting && (!must_wait))
sem_post(&block);
else
sem_post(&mutex);
usleep((rand() % 901) + 100);
sem_wait(&mutex);
eating--;
printf("Customer leaves: %d seats are available.\n", 5-eating);
if (eating == 0)
must_wait = false;
if ( waiting && (!must_wait))
sem_post(&block);
else
sem_post(&mutex);
return 0;
}
int main(){
int n=10,i=0,retVal=0;
pthread_t *thread;
sem_init(&mutex, 0, 1);
sem_init(&block, 0, 0);
thread = (pthread_t *) malloc (n*sizeof(pthread_t));
for (i=0; i<n; i++){
retVal = pthread_create(&thread[i], NULL, sushiBar, (void*)&i);
if (retVal != 0){
exit(EXIT_FAILURE);
}
}
for(i=0; i<n; i++){
retVal = pthread_join(thread[i],NULL);
if(retVal != 0){
exit(EXIT_FAILURE);
}
}
return 0;
}
【问题讨论】:
标签: c++ c synchronization semaphore condition-variable