哲学家吃空心粉问题

//       pe.c
//       哲学家吃空心粉的问题
//       Copyright 2011 shiweifu <shiweifu@126.com>
//       

#define  _REENTRANT
#include 
< stdio.h >
#include 
< unistd.h >
#include 
< stdlib.h >
#include 
< string .h >

#include 
< semaphore.h >
#include 
< pthread.h >

#define  STR_MAX 256

typedef 
struct  philosophy {
    
char  name[STR_MAX];
    sem_t 
* left;
    sem_t 
* right;
    
char  is_stop;
} philosophy;

void   * thread_function( void   * arg);

int  main( int  argc,  char   ** argv) {    
    
    
int  i  =   0 ;
    
// 五只悲剧的筷子
    sem_t sems[ 5 ];
    
// 五个NC哲学家
    philosophy philers[ 5 ];
    
    pthread_t threads[
5 ];
    
    
int  res  =   0 ;
    
    
char  tmp[ 255 =  { 0 };
    
    
for (; i  <   5 ; i ++ ) {
        philers[i].left 
=   & sems[i];
        philers[i].right 
=   & sems[i];
        
        
if  (i  ==   4 ) {
            philers[i].left 
=   & sems[ 0 ];
        }
        philers[i].is_stop 
=   0 ;
        sprintf(tmp,
" NC %d " ,i);
        strncpy(philers[i].name,tmp,
255 );
    }
    

    
for (i  =   0 ; i  <   5 ; i ++ ) {
        sem_init(
& sems[i],  0 10 );

        res 
=  pthread_create( & threads[i],NULL,thread_function, & philers[i]);
        
if  (res  !=   0 ) {
            perror(
" 创建线程出错啦... " );
        }
    }
    
    
// 给这群吃货吃20秒
    sleep( 20 );
    
    
for (i  =   0 ; i  <   5 ; i ++ ) {
        philers[i].is_stop 
=   1 ;
        pthread_join(threads[i],NULL);
        
    }
    
for (i  =   0 ; i  <   5 ; i ++ ) {
        sem_destroy(
& sems[i]);
    }

    exit(EXIT_SUCCESS);
}

void   * thread_function( void   * arg) {
    philosophy 
* =  arg;
    
    
while  ( 1 ) {
        
if  (sem_trywait(p -> left)  ==   0 ) {
            
if  (sem_trywait(p -> right)  ==   0 ) {
                printf(
" 红烧翅膀真好吃,我是%s\n " ,p -> name);
                sem_post(p
-> left);
                sem_post(p
-> right);
                sleep(
1 );

            } 
else  {
                sem_post(p
-> left);
            }
        }
        
if  (p -> is_stop  ==   1 ) {
            
break ;
        }
    }
    pthread_exit(NULL);
}

转载于:https://www.cnblogs.com/shiweifu/archive/2011/04/29/2033120.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值