Posted on 2008-01-04 00:13
山泉弯延 阅读(269)
评论(0) 编辑 收藏 引用 所属分类:
UNIX Programming
#include "apue.h"
#include "lock.h"
#include "lock.c"
/*define some important variable*/
/*=======================================*/
pid_t pid;
static char *forks[5]={
"fork0", "fork1", "fork2" ,"fork3" ,"fork4"
};
static int necs;
#define N 5
/*======================================*/
void takeFork(int i)
{
if(i==N-1)
{
lock(forks[0]);
lock(forks[i]);
}
else
{
lock(forks[i]);
lock(forks[i+1]);
}
}
void putFork(int i)
{
if(i==N-1)
{
unlock(forks[0]);
unlock(forks[i]);
}
else
{
unlock(forks[i]);
unlock(forks[i+1]);
}
}
int
thinking(int i,int necs){
printf("pholosopher %d is thinking\n",i);
return sleep(necs);
}
int
eating(int i,int necs)
{printf("pholosopher %d is eating\n",i);
return sleep(necs);
}
void philosopher(int i)
{
while(1)
{
thinking(i,necs);
takeFork(i);
eating(i,necs);
putFork(i);
}
}
int
main(int argc ,char *argv[])
{
if(argc=1)
necs=2;
else if(argc==2)
necs=atoi(argv[1]);
else return 0;
int i;
for(i=0;i<N;i++)
{
pid=fork();
if(pid ==0)
philosopher(i);
}
return 0;
}