#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
int chop = 5;
sem_t Get_number, Put_number;
void *sign(void *num)
{
int flag = 0;
while(1)
{
flag = (flag == 0 ? 1:0);
if(flag)
{
sem_wait(&Get_number);
chop--;
printf("%d person get one \n", (int)num);
}
else if(sem_trywait(&Get_number) == 0)
{
printf("%d just begin eat...\n",(int)num);
sleep(rand()%5);
sem_post(&Get_number);
sem_post(&Get_number);
}
else
sem_post(&Get_number);
sleep(2);
}
}
int main(void)
{
pthread_t tid[5];
int i = 0;
sem_init(&Get_number, 0, 5);
for(;i < 5; i++)
pthread_create(&tid[i], NULL, sign, (void *)i);
for(i = 0; i < 5; i++)
pthread_join(tid[i], NULL);
sem_destroy(&Get_number);
return 0;
}
哲学家就餐-信号量
最新推荐文章于 2024-04-05 09:00:00 发布