实验一
一、实验名称:哲学家就餐问题的实现 二、实验学时: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
#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下载服务。
相关推荐: