식사하는 철학자 코드인데요
글쓴이: ghdhddl79 / 작성시간: 화, 2017/05/09 - 7:15오후
#define N 5 /* number of philosophers */ #define LEFT (i + N - 1) % N /* number of i's left neighbor */ #define RIGHT (i + 1) % N /* number of i's right neighbor */ #define THINKING 0 /* philosopher is thinking */ #define HUNGRY 1 /* philosopher is trying to get forks */ #define EATING 2 /* philosopher is eating */ typedef int semaphore; /* semaphores are a special kind of int */ int state[N]; /* array to keep track of everyone's state */ semaphore mutex = 1 ; /* mutual exclusion for critical regions */ semaphore s[N]; /* one semaphore per philosopher */ void philosopher(int i) /* i: philosopher number, from 0 to N-1 */ { while (TRUE) { /* repeat forever */ think( ); /* philosopher is thinking */ take_forks(i); /* acquire two forks or block */ eat(); /* yum-yum, spaghetti */ put_forks(i); /* put both forks back on table */ } } void take_forks(int i) /* i: philosopher number, from 0 to N-1 */ { down(&mutex); /* enter critical region */ state[i] = HUNGRY; /* record fact that philosopher i is hungry */ test(i); /* try to acquire 2 forks */ up(&mutex); /* exit critical region */ down(&s[i]); /* block if forks were not acquired */ } void put_forks(i) /* i: philosopher number, from 0 to N-1 */ { down(&mutex); /* enter critical region */ state[i] = THINKING; /* philosopher has finished eating */ test(LEFT); /* see if left neighbor can now eat */ test(RIGHT); /* see if right neighbor can now eat */ up(&mutex); /* exit critical region */ } void test(i) /* i: philosopher number, from 0 to N-1 */ { if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) { state[i] = EATING; up(&s[i]); } }
-----------------------------------------------------
여기서 put_forks에서 state[i]=THINKING을
test(left) (rihgt) 호출 후에 적으면 어떻게 되나요?
이해가 잘안되서 질문드려요
잘보이시면 첨부파일 보시면됩니다
File attachments:
첨부 | 파일 크기 |
---|---|
![]() | 87.88 KB |
Forums:
eating 함수의 소스 코드는 없군요. 일단 이
eating 함수의 소스 코드는 없군요. 일단 이 함수가 아무 일도 하지 않는다고 가정한다면...
put_forks가 호출되는 시점에서 state[i]는 어떤 값을 가질까요?
그것을 THINKING으로 업데이트하지 않는다면 이후의 test(LEFT); 및 test(RIGHT);의 동작에는 어떤 영향을 줄까요?
직접 생각해보세요.
댓글 달기