www.pudn.com > threadphilosopher.rar > 6.c
#include "ourhdr.h"
#include "semaphore.h"
#include "fcntl.h"
#include "sys/types.h"
#include "pthread.h"
#include "error.c"
sem_t mutex[5]; //设置五个信号代表五个叉子
int times;
void eat(int i); //吃饭函数
void think(int i); //思考函数
void *philosopher(void *ptr); //哲学家函数
int main(int argc,char *argv[])
{
pthread_t ph[5]; //设置五个线程代表五个哲学家
int i,status;
if(argc==1) //默认时间为2秒
times=2;
else{
if(strcmp(argv[1],"-t")!=0){ //按输入的数值改变times值
printf("input format error!\n");
return;
}
else
times=atoi(argv[2]);
}
for(i=0;i<5;i++) //初始化五个信号量的值为1,即可取
sem_init(&mutex[i],0,1);
for(i=0;i<5;i++){ //初始化五个哲学家的值及启动程序
status=pthread_create(&ph[i],NULL,philosopher,(void *)i);
if(status!=0)
err_sys("error!");
}
for(i=0;i<5;i++) //等待5个线程
pthread_join(ph[i],NULL);
}
void *philosopher(void *ptr)
{
int i,n;
i=(int)ptr;
while(1){
think(i); //思考
if(i%2==0){ //偶数哲学家先等待左边叉子再等待右边叉子
sem_wait(&mutex[i]);
sem_wait(&mutex[(i+1)%5]);
}
else{ //否则顺序相反
sem_wait(&mutex[(i+1)%5]);
sem_wait(&mutex[i]);
}
eat(i); //吃饭
if(i%2==0){ //偶数哲学家先放下左边叉子再放下右边叉子
sem_post(&mutex[i]);
sem_post(&mutex[(i+1)%5]);
}
else{ //否则顺序相反
sem_post(&mutex[(i+1)%5]);
sem_post(&mutex[i]);
}
}
}
void think(int i)
{
printf("philosopher %d is thinking.\n",i);
sleep(times);
return;
}
void eat(int i)
{
printf("philosopher %d is eating.\n",i);
sleep(times);
return;
}