操作系统学习笔记(13) 互斥与同步的经典问题 -哲学家进餐问题

  1 哲学家进餐问题:
  2 (算法)信号量方法:
  3     //Program diningphilosophers
  4     var fork:array[5] of semaphore = 1;
  5     int i;
  6
  7     procedure philosopher(int i){
  8         while(true){
  9             think;
 10             wait(fork[i]);
 11             wait(fork[(i+1)%5]);
 12             eat();
 13             siganl(fork[(i+1)%5]);
 14             signal(fork[i]);
 15         }
 16     }
 17
 18     main(){
 19         philosopher(0);
 20         philosopher(1);
 21         philosopher(2);
 22         philosopher(3);
 23         philosopher(4);
 24     }
 25
 26     哲学家只能竞争左右两只筷子。
 27     可能会出现死锁现象:
 28
 29     改进方案:(增加一个资源)
 30     //Program diningphilosophers
 31     var fork:array[5] of semaphore = 1;
 32     int i;
 33     var room :semaphore = 4;
 34    
 35     procedure philosopher(int i){
 36         while(true){
 37             think;
 38             wait(room);
 39             wait(fork[i]);
 40             wait(fork[(i+1)%5]);
 41             eat();
 42             siganl(fork[(i+1)%5]);
 43             signal(fork[i]);
 44             signal(room);
 45         }
 46     }
 47
 48     main(){
 49         philosopher(0);
 50         philosopher(1);
 51         philosopher(2);
 52         philosopher(3);
 53         philosopher(4);
 54     }

你可能感兴趣的:(算法,Semaphore,Signal)