第一范文网 - 专业文章范例文档资料分享平台

哲学家就餐问题

来源:用户分享 时间:2020-06-20 本文由陌人不故 分享 下载这篇文档 手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

实验一

一、实验名称:哲学家就餐问题的实现 二、实验学时:2 三、实验内容和目的:

实验目的:实现哲学家就餐问题,要求不能出现死锁。通过本实验熟悉Linux系统的基本环境,了解Linux下进程和线程的实现。

实验内容:在Unix系统下实现教材2.4.2节中所描述的哲学家就餐问题。要求显示出每个哲学家的工作状态,如吃饭,思考。连续运行30次以上都未出现死锁现象。

四、实验原理:

由Dijkstra提出并解决的哲学家进餐问题(The Dinning Philosophers Problem)是典型的同步问题。该问题是描述有五个哲学家共用一张圆桌,分别坐在周围的五张椅子上,在圆桌上有五个碗和五只筷子,他们的生活方式是交替地进行思考和进餐。平时,一个哲学家进行思考,饥饿时便试图取用其左右最靠近他的筷子,只有在他拿到两只筷子时才能进餐。进餐完毕,放下筷子继续思考。

五、实验器材(设备、元器件)

(1) 学生每人一台PC,安装WindowsXP/2000操作系统。 (2) 局域网络环境。

(3) 个人PC安装VMware虚拟机和Ubuntu系统。

六、实验内容:

(一) 熟悉Ubuntu系统下的多线程编程。 (二)实现哲学家就餐问题 1. 算法思想

规定奇数号哲学家先拿他左边的筷子,然后再去拿右边的筷子,而偶数号哲

学家则相反。按此规定,将是1、2号哲学家竞争1号筷子;3、4号哲学家竞争3号筷子。即五位哲学家都生竞争奇数号筷子,获得后,再去竞争偶数号筷子,最后总会有一位哲学家能获得两只筷子而进餐。

2. 流程图

结束 拿起左右手筷子 放下左右手筷子 开始 正在等待 否 正在进餐 否 是 是 否 正在思考 是 状态为进餐 状态为思考 状态为等待 3. 程序代码(重要代码请注释)

#include #include #include #include #include

#define NOC 5 //number of chopstic #define NOP 5 //number of philosopher

sem_t chopstic[NOC]; //semaphore int flag[5]; //philosopher's status

void *eat(int i){ int position; int temp = 0; int j = (i+1)%NOC; position = i%2; while(1){ if(position == 0){ //odd take left first sem_wait(&chopstic[i]); printf(\ sem_wait(&chopstic[j]); printf(\ flag[i] = 1; //philosopher is eating printf(\//print others' status while(temp < 5){ if(!flag[temp]) printf(\ temp++; } temp = 0; printf(\ printf(\print others' status

while(temp < 5){ if(flag[temp]) printf(\ temp++; }

printf(\temp = 0;

//printf(\sleep(2); flag[i] = 0;

printf(\sem_post(&chopstic[i]);

printf(\sem_post(&chopstic[j]); }

else{ //even take right first sem_wait(&chopstic[j]);

printf(\sem_wait(&chopstic[i]);

printf(\flag[i] = 1;

printf(\while(temp < 5){ if(!flag[temp]) printf(\ temp++; }

temp = 0; printf(\

printf(\while(temp < 5){ if(flag[temp]) printf(\ temp++;

} printf(\ temp = 0; //printf(\ sleep(2); flag[i] = 0; printf(\ sem_post(&chopstic[j]); printf(\ sem_post(&chopstic[i]); } } }

int main(void){ int i = 0; int error; pthread_t philosopher[NOP]; //init sem while(i < 5){ flag[i] = 0; sem_init(&chopstic[i], 0, 1); i++; } i = 0; //create thread while(i < 5){ error = pthread_create(&philosopher[i], NULL, (void *)eat, (void *)i); if(error){ printf(\ exit(0); } i++; }

搜索“diyifanwen.net”或“第一范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,第一范文网,提供最新医药卫生哲学家就餐问题 全文阅读和word下载服务。

哲学家就餐问题 .doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/wenku/1087393.html(转载请注明文章来源)
热门推荐
Copyright © 2018-2022 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top