- 1、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
- 4、该文档为VIP文档,如果想要下载,成为VIP会员后,下载免费。
- 5、成为VIP后,下载本文档将扣除1次下载权益。下载后,不支持退款、换文档。如有疑问请联系我们。
- 6、成为VIP后,您将拥有八大权益,权益包括:VIP文档下载权益、阅读免打扰、文档格式转换、高级专利检索、专属身份标志、高级客服、多端互通、版权登记。
- 7、VIP文档为合作方或网友上传,每下载1次, 网站将根据用户上传文档的质量评分、类型等,对文档贡献者给予高额补贴、流量扶持。如果你也想贡献VIP文档。上传文档
查看更多
哲学家就餐问题代码哲学家就餐问题代码
#includestdio.h
#includestdlib.h
#includestring.h
#includepthread.h
#includesemaphore.h
#includesys/types.h
#includeerrno.h
#includeunistd.h
#includesignal.h
#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;iCHOP_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;i4;i++)chairflg[i][0]=0;
/*create the threads*/
for(i=0;iNUM_THREADS_P;i++)
pthread_create(threads_p[i],NULL,(void*)philosopher_thread,(void*)(i));
/*wait the threads to exit*/
for(i=0;iNUM_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;iCHAIR_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;iCHAIR_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);
s
您可能关注的文档
最近下载
- 小升初自我介绍集锦.docx VIP
- 气体绝缘金属封闭开关设备特高频法局部放电在线监测装置技术规范 QGDW 11311-2021.docx VIP
- 中央八项规定精神学习解读新版课件.pptx VIP
- 电工仪表与测量第六版完整版全套PPT电子课件教案.pptx
- 材料科学基础 第2版 教学课件 作者 石德珂 西安交通大学 主编 第二章 材料中的晶体结构.ppt VIP
- 2023扬州龙川控股集团有限责任公司招聘试题及答案解析.docx
- 中小学生成式人工智能使用指南(2025年版).pdf
- 2024年辽宁省第二届职业技能大赛(快件处理员赛项)理论参考试题库(含答案).doc VIP
- 手册-—机电安装工程质量通病案例及防治手册.doc VIP
- 无偿献血宣传招募培训资料抓好血站内涵建设是保证临床安全输血的重要条件课件.ppt VIP
文档评论(0)