我正在使用信号量在c中实现餐饮哲学家的问题。我的代码工作,虽然我很困惑为什么没有发生死锁。
CODE:
#include<stdio.h>
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>
sem_t cs[5];
pthread_t phils[5];
void pickup(int i){
int k = (i+1)%5;
printf("%d: HUNGRY %d %d \n",i+1,i,k);
sem_wait(&cs[i]);
sem_wait(&cs[k]);
}
void putdown(int i){
sem_post(&cs[i]);
sem_post(&cs[(i+1) % 5]);
printf("%d: THINK \n",i+1);
}
void eat(int i){
printf("%d: EAT\n",i+1);
}
void phil(void *i){
while(1){
usleep((rand()% 100000) + 100000);
int n= *(int*)i;
pickup(n);
eat(n);
putdown(n);
}
}
int main(){
int id[5];
while(1){
for(int i = 0; i<5;i++){
sem_init(&cs[i], 0, 1);
id[i]=i;
pthread_create (&phils[i], NULL, (void *) &phil, (void *) &id[i]);
}
sleep(100);
}
}
OUTPUT的块:
2: HUNGRY 1 2
2: EAT
2: THINK
4: HUNGRY 3 4
4: EAT
4: THINK
5: HUNGRY 4 0
5: EAT
5: THINK
1: HUNGRY 0 1
1: EAT
1: THINK
3: HUNGRY 2 3
3: EAT
3: THINK
5: HUNGRY 4 0
5: EAT
5: THINK
4: HUNGRY 3 4
4: EAT
4: THINK
2: HUNGRY 1 2
2: EAT
2: THINK
1: HUNGRY 0 1
1: EAT
1: THINK
3: HUNGRY 2 3
3: EAT
3: THINK
2: HUNGRY 1 2
2: EAT
2: THINK
5: HUNGRY 4 0
5: EAT
5: THINK
4: HUNGRY 3 4
4: EAT
4: THINK
1: HUNGRY 0 1
1: EAT
1: THINK
2: HUNGRY 1 2
2: EAT
2: THINK
3: HUNGRY 2 3
3: EAT
3: THINK
4: HUNGRY 3 4
4: EAT
4: THINK
1: HUNGRY 0 1
1: EAT
1: THINK
5: HUNGRY 4 0
5: EAT
5: THINK
2: HUNGRY 1 2
2: EAT
2: THINK
3: HUNGRY 2 3
3: EAT
3: THINK
4: HUNGRY 3 4
4: EAT
4: THINK
1: HUNGRY 0 1
1: EAT
1: THINK
5: HUNGRY 4 0
5: EAT
5: THINK
我知道这是一件好事,但似乎我的线程一个接一个地执行而不是同时执行,这会破坏线程的点。
提前致谢!