修改上面的代码解决哲学家用餐死锁问题

#include
#include
#include
#include

#define N 5

sem_t chopstick[N];//筷子信号量

//哲学家线程函数
void* philosopher(void* arg){
int i = (int)arg;//哲学家序号

for(;;){
    //思考
    printf("[%d] I'm thinking...\n",i);
    sleep(rand()%3);//休眠随机时间,不超过3秒

    //等待筷子
    sem_wait(&chopstick[i]);
    sem_wait(&chopstick[(i+1)%N]);

    //就餐
    printf("\t\t\t[%d]I'm eating...\n",i);
    sleep(rand()%3);//休眠随机时间,不超过3秒

    //放回筷子
    sem_post(&chopstick[i]);
    sem_post(&chopstick[(i+1)%N]);
}

}

int main(){
pthread_t id[N];
int i;

for(i=0;i<N;i++)
   sem_init(&chopstick[i],0,1);

for(i=0;i<N;i++)
   pthread_create(&id[i],NULL,philosopher,(void*)i);

for(i=0;i<N;i++)
   pthread_join(id[i],NULL);

}

https://blog.csdn.net/gao23191879/article/details/75168867/