newplan

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

五个哲学家线程实现

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


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