#include<stdio.h>
#include<pthread.h>
int chop = 5;
pthread_mutex_t lockG = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lockP = PTHREAD_MUTEX_INITIALIZER;
void *phlio(void *num)
{
int i = (int)num;
int left = 0;
int flag = 0;
int err = 0;
while(1)
{
flag =(flag == 0? 1:0); //1 手里没有筷子,0 手里有一支
if(flag)
{
pthread_mutex_lock(&lockG); //挂起等待
if(chop > 0)
{ chop--;
printf("person %d Get 1\n", i);
}
pthread_mutex_unlock(&lockG);
}
else if((err = pthread_mutex_trylock(&lockG)) == 0) //已有筷子,尝试拿第二支
{
if (chop > 0)
{
printf("person %d Get two and begin eat..\n", i);
sleep(rand()%5);
printf("person %d End\n", i);
pthread_mutex_lock(&lockP); //吃完返回筷子
chop += 1;
pthread_mutex_unlock(&lockP);
}
pthread_mutex_unlock(&lockG);
}
else //第二次没有拿到 ,把一次筷子放回
{
pthread_mutex_lock(&lockP);
chop += 1;
pthread_mutex_unlock(&lockP);
}
usleep(1000); //延时,让第一支筷子多拿会...
}
}
int main(void)
{
pthread_t tid[5];
int i = 0;
for(; i < 5; i++)
pthread_create(&tid[i], NULL, phlio, (void *)i);
for(; i >0; i--)
pthread_join(tid[i-1], NULL);
return 0;
}
哲学家就餐--互斥锁
最新推荐文章于 2023-06-21 16:42:12 发布