linux 多线程下互斥锁实现哲学家用餐模型

#include 
#include 
#include 
#include 

pthread_mutex_t m[5];//定义5把锁
//哲学家i左边的筷子编号为i,右边筷子编号为i+1
void *tfn(void *arg)
{
	int i, l, r;

	srand(time(NULL));
	i = (int)arg;

	if (i == 4)//4号哲学家先拿右边筷子,再拿左边筷子,防止死锁
		l = 0, r = i;
	else
		l = i; r = i+1;//其余哲学家先拿左边筷子,再拿右边筷子

	while (1) 
	{
		pthread_mutex_lock(&m[l]);
		if (pthread_mutex_trylock(&m[r]) == 0) //返回值为0表示右边的筷子成功拿到
		{
			printf("\t%c is eating \n", 'A'+i);
			pthread_mutex_unlock(&m[r]);
		}
		pthread_mutex_unlock(&m[l]);
		sleep(rand() % 5);
	}

	return NULL;
}

int main(void)
{
	int i;
	pthread_t tid[5];
	
	for (i = 0; i < 5; i++)
		pthread_mutex_init(&m[i], NULL);

	for (i = 0; i < 5; i++)
		pthread_create(&tid[i], NULL, tfn, (void *)i);

	for (i = 0; i < 5; i++)
		pthread_join(tid[i], NULL);

	for (i = 0; i < 5; i++)
		pthread_mutex_destroy(&m[i]);

	return 0;
}


linux 多线程下互斥锁实现哲学家用餐模型_第1张图片

你可能感兴趣的:(Linux基础)