home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.unix.programmer
- Path: sparky!uunet!munnari.oz.au!newsroom.utas.edu.au!cam!esk!kleung
- From: kleung@esk.compserv.utas.edu.au (Kam Leung)
- Subject: implementation of semaphores in unix
- Message-ID: <1992Aug27.115017.21484@cam.compserv.utas.edu.au>
- Sender: kleung@esk.compserv.utas.edu.au
- Organization: University of Tasmania at Launceston
- References: <1992Aug21.140244.12486@walter.cray.com>
- Date: Thu, 27 Aug 92 11:50:17 GMT
- Lines: 74
-
-
- Dear guys,
- I have a difficulty in enforcing the mutual exclusion between
- 5 philosophers because I couldn't effectively change the global
- variables such as the major semaphore (me), and the private semaphore
- (s[i]). Could anybody suggest an answer for me or comment on my logic
- below. Your kind attention is much appreciated. Thanks...
-
- Regards
- Keith LEUNG
- kleung@esk.compserv.utas.edu.au
-
- #include <stdio.h>
- #include <sys/types.h>
- #define N 6
- int s[N], me;
- enum status {nthinking,vhungry,neating} ;
- enum status p[N];
- main()
- {
- int i, ;
- void PHILOSOPHER(),
- think(), eat(), hungry();
-
- me = 1; /* initial open state of main semaphore */
-
- for (i=1;i<N;i++) /*initialise 1-5 philosophers to thinking*/
- { s[i] = 0; p[i] = nthinking;} /* private semaphore s[i]=0,close*/
-
- for (i=1; i<N; i++){
- if (fork() == 0) PHILOSOPHER(i);
- }
- ..
- ..
- kill(0,9);
- }
- void PHILOSOPHER(i)
- int i;
- {
- think(i);
- -----------waitfor(me);
- ! /* see whether the sem. is open(me=1) or close(me=0)
- ! if me=1, pass thru, and set the me back to 0 */
- ! hungry(i);
- ! philosopher i = hungry
- ! printf("\nphil %d has gone into c.s.",i);
- ! check if the lefthand and righthand philosopher 'not eating'
- ! if it is so, set itself = eating, release private sem.
- ! of itself : signalto(p[i]) -- supposed to set p[i] = 1
- ! but didn't......
- --------- signalto(me);
- waitfor(s[i]);
- eat(i);
- -------- waitfor(me);
- ! ..
- ! ..
- ! activate the neigbouring philosophers (ready to eat)
- ! ..
- ! ..
- ----------signalto(me);
- printf("phil %d has finished eating and asking other to eat" );
-
- waitfor(i)
- int i;
- {
- if (i >= 1) { i--; }
- else
- { waitfor(i); }
- return i;
- }
- signalto(i)
- int i;
- {return i++;}
-
-