linux 利用互斥锁解决五哲学家问题

分享一段自己写的在Linux系统下使用互斥锁模拟解决五哲学家进餐问题的代码,编译时记得加参数: -lpthread -std=c99
// 因为课程原因又重新调整一下代码,但使用老网站编辑器时多了一些乱码,不知道怎么回事


#include 
#include 
#include 

#include 
#include 
#include "pthread.h"

#define NUM_MAX 5
#define NUM 6
struct prodcons 
{
	int num;
	int test;
	pthread_mutex_t lock;	
	pthread_cond_t notuse;
};

void init (struct prodcons *prod);
int lock (struct prodcons *prod);
void unlock (struct prodcons *prod);
void *philosopher (int n);
//void manager (void *data);

struct prodcons buffer[NUM];
struct prodcons *r;

int main (int argc,char *argv[])
{
	pthread_t th_1,th_2,th_3,th_4,th_5,th_m;
	void *retval;
	for (int c=0;clock,NULL);
	pthread_cond_init (&prod->notuse,NULL);
	
}

int lock (struct prodcons *prod)
{
	return pthread_mutex_lock(&prod->lock);
//	prod->test=2;
//	printf("%d\n",prod->test);
//	while(!(pthread_cond_wait(&prod->notuse,NULL)));
		
}
void unlock (struct prodcons *prod)
{
	pthread_mutex_unlock(&prod->lock);
	
}
void *philosopher(int n)
{
	if (n == NUM_MAX)
	{
		while(1)
		{
		int h=1,g=1;
		while (1)
		{
			h = lock(&buffer[0]);
			g = lock(&buffer[n-1]);
			if (g)
			{
				unlock(&buffer[n-1]);
				printf("not get two together,put one\n");
			}
			if (h)
			{
				unlock(&buffer[0]);
				printf("not get two together,put one\n");
			}
			if(h == 0 && g == 0) 
			{
				printf("P%d get two.\n",n);
				break;
			}
		}
		printf("P%d is eating.\n",n);
		sleep(1);
		unlock(&buffer[0]);
		unlock(&buffer[n-1]);
		printf("P%d is thinking.\n",n);
		sleep(1);
		}
		return NULL;		
	}
	else
	{
		while(1)
		{
		int h=1,g=1;
		while (1)
		{
			h = lock(&buffer[n]);
			g = lock(&buffer[n-1]);
			if (g)
			{
				unlock(&buffer[n]);
				printf("not get two together,put one\n");
			}
			if (h)
			{
				unlock(&buffer[n-1]);
				printf("not get two together,put one\n");
			}
			if(h == 0 && g == 0) 
			{
				printf("P%d get two.\n",n);
				break;
			}
		}
		printf("P%d is eating.\n",n);
		sleep(1);
		unlock(&buffer[n]);
		unlock(&buffer[n-1]);
		printf("P%d is thinking.\n",n);
		sleep(1);
		}
		return NULL;
	}	
}
/*
void manager (void *data)
{
	for (int z=0;z<5;z++)
	{
		for (r=buffer;rnotuse);
		}
		sleep(3);
	}
} 
*/




 
  
 
 

你可能感兴趣的:(linux)