#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
sem_t room;
sem_t chopstick[5];
void* eat(void *num)
{
int numb=(int)num;
while(1)
{
printf("number:%d thinking...\n",numb);
sem_wait(&room);
sem_wait(&chopstick[numb]);
sem_wait(&chopstick[(numb+1)%5]);
printf("thinker:%d eat...\n",numb);
sem_post(&chopstick[numb]);
sem_post(&chopstick[(numb+1)%5]);
sem_post(&room);
sleep(1);
}
}
void main()
{
pthread_t thinker[5];
sem_init(&room,0,3); //房间里只能容纳4个人
int i;
for(i=0;i<5;i++) //总共有5只筷子
sem_init(&chopstick[i],0,1);
for(i=0;i<5;i++)
pthread_create(&thinker[i], NULL, eat,(void*)i);
for(i=0;i<5;i++)
pthread_join(thinker[i], NULL);
}
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
sem_t room;
sem_t chopstick[5];
void* eat(void *num)
{
int numb=(int)num;
while(1)
{
printf("number:%d thinking...\n",numb);
sem_wait(&room);
sem_wait(&chopstick[numb]);
sem_wait(&chopstick[(numb+1)%5]);
printf("thinker:%d eat...\n",numb);
sem_post(&chopstick[numb]);
sem_post(&chopstick[(numb+1)%5]);
sem_post(&room);
sleep(1);
}
}
void main()
{
pthread_t thinker[5];
sem_init(&room,0,3); //房间里只能容纳4个人
int i;
for(i=0;i<5;i++) //总共有5只筷子
sem_init(&chopstick[i],0,1);
for(i=0;i<5;i++)
pthread_create(&thinker[i], NULL, eat,(void*)i);
for(i=0;i<5;i++)
pthread_join(thinker[i], NULL);
}