1 / 5

经典问题:哲学家就餐问题

经典问题:哲学家就餐问题. 计科 42 1924223 陶益坤 2006.9.29. 临界资源. 问题描述:. 五个哲学家坐在圆桌前,每人一份炒饭; 每个哲学家两侧各有一支筷子; 哲学家处于吃饭和思考两种状态。. 利用记录型信号量解决. #define N 5 void philosopher (int i) { while (true) { 思考; 取 chopstick[i]; 取 chopstick [(i+1) % 5] ; 进食; 放 chopstick [i];

ezra-pace
Download Presentation

经典问题:哲学家就餐问题

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 经典问题:哲学家就餐问题 计科42 1924223 陶益坤 2006.9.29

  2. 临界资源 问题描述: 五个哲学家坐在圆桌前,每人一份炒饭; 每个哲学家两侧各有一支筷子; 哲学家处于吃饭和思考两种状态。

  3. 利用记录型信号量解决 #define N 5 void philosopher (int i) { while (true) { 思考; 取chopstick[i]; 取chopstick [(i+1) % 5]; 进食; 放chopstick [i]; 放chopstick [(i+1) % 5]; } }

  4. 为防止死锁发生可采取的措施: • 最多允许4个哲学家同时去拿左边的筷子 • 仅当一个哲学家左右两边的筷子都可用时,才允许他拿筷子() • 给所有哲学家编号,奇数号的哲学家必须首先拿左边的筷子,偶数号的哲学家则反之

  5. void philosopher (int i) { while (true) { 思考; P(&mutex); state[i] = HUNGRY; test(i); V(&mutex); P(&s[i]); 拿左筷子;拿右筷子; 进食; 放左筷子;放右筷子; P(&mutex) state[ i ] = THINKING; test([i-1] % 5); test([i+1] % 5); V(&mutex); } } state[ i ] = THINKING s[ i ] = 0 #define N 5 #define THINKING 0 #define HUNGRY 1 #define EATING 2 #typedef int semaphore; int state[N]; semaphore mutex=1; semaphore s[N]; void test(int i) { if (state[ i ] == HUNGRY) && (state [ (i-1) % 5] != EATING) && (state [ (i+1) % 5] != EATING) { state[ i ] = EATING; V(&s[ i ]); } }

More Related