Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1337987
  • 博文数量: 1334
  • 博客积分: 645
  • 博客等级: 上士
  • 技术积分: 5762
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-25 16:56
文章分类

全部博文(1334)

文章存档

2014年(108)

2013年(1059)

2012年(169)

分类:

2012-10-30 13:17:39

      题目:有五个哲学家共用一张圆桌,分别坐在周围的五张椅子上,在桌上有五个碗和五只筷子,他们的生活

方式是思考和进餐。平时,一个哲学家进行思考,饥饿时就便试图去他们呢左右的筷子来就餐。只有在他拿到两

个筷子时才能就餐。

  分析: 哲学家思考问题时,他旁边的筷子允许被别的哲学家拿起。因此,筷子为临界资源

  实现:

      process i

           repate :

                 思考;

           p[c[i]];

           p[c[i+1]]mod 5;

           进食

           v[c[i]];

           v[c[i+1]]mod 5;

      unfail flase;

但是可能会产生死锁:一个哲学家只拿到一个筷子。

1>再加一个筷子

2>给个时间限定t,如果处于死锁状态且持续时间超过t,则该进程放弃自己拥有的资源,放入就需队列。

3>只允许其中4个哲学家先竞争。

4>在拥有坐筷子情况下,试着去判断右筷子是否空闲,如果空闲则拿起右筷子否则将左筷子释放。

代码实现:

文件 local_eat.h

点击(此处)折叠或打开

  1. #ifndef _LOCAL_EAT_H
  2. #define _LOCAL_EAT_H

  3. #include<stdio.h>
  4. #include<unistd.h>
  5. #include<pthread.h>
  6. #include<sys/types.h>

  7. #define MAX 5
  8. pthread_mutex_t mutex[MAX];
  9. pthread_cond_t cond[MAX];
  10. char name[MAX][20] = {"laozi","makesi","engesi","xunzi","sugeladi"};

  11. void* eating(void * counter);
  12. #endif

文件phil.c

点击(此处)折叠或打开

  1. #include"local_eat.h"

  2. void * eating(void *counter)
  3. {
  4.     int cnt = *((int*)counter);

  5.     printf("%d :%s is thinking\n",cnt,name[cnt]);
  6.     while(1) {
  7.         pthread_mutex_lock(mutex+cnt);
  8.         if(!pthread_mutex_trylock(mutex+((cnt+1)%MAX)))
  9.             //pthread_cond_wait(cond+(cnt+1)%MAX,mutex+((cnt+1)%MAX));
  10.             pthread_cond_wait(cond+cnt,mutex+cnt);
  11.         printf("%d :%s is eating\n",cnt,name[cnt]);
  12.         printf("%d :%s has eat up\n",cnt,name[cnt]);
  13.         pthread_mutex_unlock(mutex+cnt);
  14.         pthread_mutex_unlock(mutex+((cnt+1)%MAX));
  15.         //pthread_cond_signal(cond+((cnt+1)%MAX));
  16.         pthread_cond_signal(cond+cnt);
  17.         sleep(1);
  18.     }
  19.     return NULL;
  20. }
  21. int main()
  22. {
  23.     int index = 0;
  24.     pthread_t pthread[MAX];

  25.     for(index = 0; index < MAX;index++)
  26.          pthread_mutex_init(mutex+index,NULL);
  27.     for(index =0; index< MAX;index++)
  28.          pthread_cond_init(cond+index,NULL);
  29.     for(index=0;index<MAX;index++){
  30.         printf(" index = %d\n",index);
  31.         pthread_create(pthread+index,NULL,(void*)eating,(void*)&index);
  32.     }
  33.    
  34.     for(index = 0; index < MAX;index++)
  35.          pthread_mutex_destroy(mutex+index);
  36.     for(index =0; index< MAX;index++)
  37.          pthread_cond_destroy(cond+index);
  38.     return 0;
  39. }

阅读(392) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~