分享一段自己写的在Linux系统下使用互斥锁模拟解决五哲学家进餐问题的代码,编译时记得加参数: -lpthread -std=c99
// 因为课程原因又重新调整一下代码,但使用老网站编辑器时多了一些乱码,不知道怎么回事
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/syscall.h>
#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;c<NUM;c++)
{
init(&buffer[c]);
}
pthread_create (&th_1, NULL, philosopher, 1);
pthread_create (&th_2, NULL, philosopher, 2);
pthread_create (&th_3, NULL, philosopher, 3);
pthread_create (&th_4, NULL, philosopher, 4);
pthread_create (&th_5, NULL, philosopher, 5);
// pthread_create (&th_m, NULL, manager, 0);
pthread_join (th_1, &retval);
pthread_join (th_2, &retval);
pthread_join (th_3, &retval);
pthread_join (th_4, &retval);
pthread_join (th_5, &retval);
return 0;
}
void init (struct prodcons *prod)
{
pthread_mutex_init (&prod->lock,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;r<buffer+5;r++)
{
pthread_cond_signal(&buffer->notuse);
}
sleep(3);
}
}
*/