哲学家就餐问题代码.doc

  1. 1、本文档共14页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
哲学家就餐问题代码

#include #include #include #include #include #include #include #include #include #define NUM_THREADS_P 5 /*define the number of philosopher*/ #define CHAIR_NUM 4 #define CHOP_NUM 5 int chairflg[CHAIR_NUM][2],dining_num 0; sem_t chair,chopsticks[CHOP_NUM],mutex,mutex1,print_mutex;// 设定信号量 pthread_t threads_p[NUM_THREADS_P]; /*philosopher*/ void* philosopher_thread int tid ; int main int i; sem_init chair,0,CHAIR_NUM ; /*set the value of semaphores*/ for i 0;i CHOP_NUM;i++ sem_init chopsticks[i],0,1 ; sem_init mutex,0,1 ; sem_init mutex1,0,1 ; sem_init print_mutex,0,1 ; for i 0;i 4;i++ chairflg[i][0] 0; /*create the threads*/ for i 0;i NUM_THREADS_P;i++ pthread_create threads_p[i],NULL, void* philosopher_thread, void* i ; /*wait the threads to exit*/ for i 0;i NUM_THREADS_P;i++ pthread_join threads_p[i],NULL ; /*destroy the semaphores*/ sem_destroy chair ; sem_destroy chopsticks[CHOP_NUM] ; sem_destroy mutex ; sem_destroy mutex1 ; sem_destroy print_mutex ; return 0; void* philosopher_thread int tid int i; i tid; sem_wait chair ; sem_wait mutex ; for i 0;i CHAIR_NUM;i++ if chairflg[i][0] 0 /*the chair is empty*/ chairflg[i][0] 1; chairflg[i][1] int i;/*philosopher i toke the chair*/ break; dining_num++; sem_post mutex ; sem_wait chopsticks[i] ; printf philosopher %d get chopstics %d\n,i,i ; sem_wait chopsticks[ i+1 %CHOP_NUM] ; printf philosopher %d get chopstics %d\n,tid, i+1 %CHOP_NUM ; sleep rand %3 ; sem_wait print_mutex ; printf philosopher %d is dining.when he is dining ,there are %d philosophers at table.\n, int i,dining_num ; for i 0;i CHAIR_NUM;i++ if chairflg[i][0] 1 printf poilosopher %d in chair %d. ,chairflg[i][1],i+1 ; printf \n\n ; sem_post print_mutex ; sleep rand %3 ; sem_post chopsticks[i] ; sem_post chopsticks[ i+1 %CHOP_NUM] ; sem_wait mutex1 ; for i 0;i CHAIR_NUM;i++ if chairflg[i][1] int i chairflg[i][0] 0; break; dining_num--; sem_post mutex1 ; sem_post chair ; printf philosopher %d

文档评论(0)

hai1956012 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档