newplan

阿基米德在洗澡時發現浮力原理,高興得來不及穿㆖褲子,跑到街㆖大喊:Eureka(我找到了)。
posts - 39, comments - 26, trackbacks - 0, articles - 4
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

五个哲学家进程实现

Posted on 2008-01-04 00:13 山泉弯延 阅读(258) 评论(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;
}


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理