哲学家就餐问题

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验一

一、实验名称:哲学家就餐问题的实现

二、实验学时: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("philosopher%d get %d\n", i, i);

sem_wait(&chopstic[j]);

printf("philosopher%d get %d\n", i, j);

flag[i] = 1; //philosopher is eating

printf("waitting:"); //print others' status

while(temp < 5){

if(!flag[temp])

printf("philosopher%d\t", temp);

temp++;

}

temp = 0;

printf("\n");

printf("eating:");// print others' status

while(temp < 5){

if(flag[temp])

printf("philosopher%d\t", temp);

temp++;

}

printf("\n\n");

temp = 0;

//printf("\nphilosopher%d is eating\n\n", i); sleep(2);

flag[i] = 0;

printf("philosopher%d put %d\n", i, i); sem_post(&chopstic[i]);

printf("philosopher%d put %d\n", i, j); sem_post(&chopstic[j]);

}

else{ //even take right first

sem_wait(&chopstic[j]);

printf("philosopher%d get %d\n", i, j);

sem_wait(&chopstic[i]);

printf("philosopher%d get %d\n", i, i);

flag[i] = 1;

printf("waitting:");

while(temp < 5){

if(!flag[temp])

printf("philosopher%d\t", temp);

temp++;

}

temp = 0;

printf("\n");

printf("eating:");

while(temp < 5){

if(flag[temp])

printf("philosopher%d\t", temp);

temp++;

printf("\n\n");

temp = 0;

//printf("\nphilosopher%d is eating\n\n", i);

sleep(2);

flag[i] = 0;

printf("philosopher%d put %d\n", i, j);

sem_post(&chopstic[j]);

printf("philosopher%d put %d\n", i, i);

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("error:create thread failed!!\n");

exit(0);

}

i++;

}

相关文档
最新文档