[转] Algorithm discussion: philosopher dining problem

xiaoxiao2021-03-06  25

In 1965, Dijkstra posed and solved a synchronization problem he called thedining philosophers problem. ........ The problem can be stated quite simplyas follows. Five philosophers are seated around a circular table. Each philosopher has a plate of spaghetti. The spaghetti is so slippery that a philosopher needs two forks to eat it. Between each pair of plates is one fork. The life of a philosopher consists of alternate periods of eating and thinking. When a philosopher gets hungry, she tries to acquire her left and rightfork, one at a time, in either order If successful in acquiring two forks, she eats for a while, then puts down the forks and continues to think Thekey question is:.. Can you write a program for each philosopher that does what IT Is Supposed to Do And Never Gets Stuck? --From Written by Andrew S. Tanenbaum Typed by Foolball: -pprogramme provike by ya:: 法 1: Using public documents Perform: #include : #include :: #include :: #include :: #include :: #define n 5: : INT I, J, T, STATUS ;:: File * f ;:: char * state [n] ;:: main ():: {: f = fopen ("/ share", "w ") ;: : PUTC (J, F) ;: if (fork ()):: {if (for ()):: {if (for (fork ()):: {ix (fork ):: {WaitPID (-1, * status, 0) ;:: fclose (f);}:: Else:: Philosophy (4);}::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: : Philosophy (2);

}:: Else:: Philosophy (1);}:: else:: philosophy (0) ;:::::::::::::: "% D% S / N", I, "is thinking") ;:: for (t = 0; t <= rand () 1000; t ) ;:: State [i = "hungry" ;:: Printf ("% D% S / N", I, "is Hungry") ;:: for (t = 0; t <= rand () 10000; t ) ;:: for (; i! = j;): : {FSEEK (F, 0L, 0) ;:: j = getc (f);}:: state [i = "eating" ;:: Printf ("% D% s / n", i, "is eat" );: J = (j 1)% N:: fseek (f, 0l, 0) ;:: PUTC (J, f) ;::}:: :: #include : #define n 4:: file * f ;:: int i, status ;:: char * state [n] ;:: void philosofy (int i) ::: {:: IF ((f = fopen ")) == NULL):: {: Printf (" cann't open this file ");::: : {: {()):: {: If (fork ()):: {: if (fork ()):: {:. IF (fork ()):: {:: i (fork ()):: {: Waitpid (-1, & status, 0) ;:: fclose (f) ;::}:: else:: philosofy (4 );:}:::}::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

转载请注明原文地址:https://www.9cbs.com/read-39822.html

New Post(0)