我是一个初学者,我正在实施餐饮哲学家的问题。但是,我遇到了一个问题。在我的哲学家()函数中,我希望我的其他线程等到左右筷子可供它们使用。我应该如何实现这个?目前,程序只是在 2 位哲学家吃完后终止,而无需等待其他人吃完
我已经尝试过:
- 使用互斥锁来锁定 philosopher() 函数中的共享变量,虽然它可以确保没有哲学家挨饿,但使用这种方法意味着放弃并发性(即使有筷子可供其他哲学家使用,也只有一个哲学家可以同时进食)利用)
- 在我的 while 循环中使用 sleep() 函数,但它也不起作用
任何帮助表示赞赏,谢谢!
代码
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#define NUM 5 // Number of Philosophers
sem_t chopSticks[NUM]; // binary semaphore for each chopstick
sem_t mutex;
int philNo[NUM] = {0, 1, 2, 3, 4};
void* philosopher(void*);
int main()
{
int semValue;
pthread_t threadId[NUM]; // 5 concurrent threads for 5 philsophers
sem_init(&mutex, 0, 1);
for(int i=0; i< NUM; i++)
sem_init(&chopSticks[i], 0, 1);
for(int i=0; i< NUM; i++)
{
pthread_create(&threadId[i], NULL, philosopher, (void*) &philNo[i]);
printf("\nPhilosopher %d is thinking", i+1);
}
for(int i=0; i< NUM; i++)
pthread_join(threadId[i], NULL);
return 0;
}
void* philosopher(void* philNo)
{
int n = *(int*) philNo;
int rightValue, leftValue;
int left = (n+4) % NUM;
int right = (n+1) % NUM;
sem_getvalue(&chopSticks[left], &leftValue);
sem_getvalue(&chopSticks[right], &rightValue);
//sem_wait(&mutex);
/* while(leftValue != 1 && rightValue != 1)
{
wait for the left and right chopsticks to be free
How should I implement this?
} */
if(leftValue == 1 && rightValue == 1) // if both left and right chopSticks are free then start eating
{
sem_wait(&chopSticks[left]);
sem_wait(&chopSticks[right]);
printf("\nPhilosopher %d has taken Chopstick-%d and Chopstick-%d", n+1, left+1, right+1);
printf("\nPhilosopher %d is Eating", n+1);
sleep(1);
sem_post(&chopSticks[left]);
sem_post(&chopSticks[right]);
printf("\nPhilosopher %d finished eating", n+1);
printf("\nPhilosopher %d has put down chopstick-%d and chopstick-%d", n+1, left+1, right+1);
}
//sem_post(&mutex);
}