Posted on 2008-01-04 00:14
山泉弯延 阅读(339)
评论(0) 编辑 收藏 引用 所属分类:
UNIX Programming
#include "apue.h"
#include "semaphore.h"
#include "pthread.h"
#define N 5
static int necs;
static sem_t *forks;
void *
takeFork(int i)
{
if(i==N-1)
{
sem_wait(&forks[0]);
sem_wait(&forks[i]);
}
else
{
sem_wait(&forks[i]);
sem_wait(&forks[i+1]);
}
}
void *
putFork(int i)
{
if(i==N-1)
{
sem_post(&forks[0]);
sem_post(&forks[i]);
}
else
{
sem_post(&forks[i]);
sem_post(&forks[i+1]);
}
}
void
thinking(int i,int necs)
{
printf("pholosopher %d is thinking\n",i);
sleep(necs);
}
void
eating(int i,int necs)
{
printf("pholosopher %d is eating\n",i);
sleep(necs);
}
void *
philosopher(void *n)
{
int i=(int )n;
while(1)
{
thinking(i,necs);
takeFork(i);
eating(i,necs);
putFork(i);
}
}
//============================main function
int
main(int argc,char *argv[])
{
pthread_t tid;
if(argc==1)
necs=2;
else if(argc ==2)
necs=atoi(argv[1]);
else return 1;
forks=(sem_t*)malloc(N*sizeof(sem_t));
int i;
for(i=0; i<N; i++)
sem_init(forks+i,0,1);
int status;
for(i=0;i<N;i++)
{
status=pthread_create(&tid,NULL,philosopher,(void*)i);
if(status<0)
err_sys("create error!");
}
pthread_join(tid ,NULL);
return 0;
}