영~~ 만만한 녀석이 아니더군요.. 이번에 기말 레포트로 나온 프로그램은.. 완전 저의 기를 죽이더군요.. 그래서 인터넷에 운영체제 고수들을 찾아 도움을 청합니다. 문제는 철학자들의 만찬에서 나타나는 문제를 해결하는 c프로그램을 작성하라 인데요...
dead-lock과 starvation 해결인거 같은데..
전혀 손도 못대고 있습니다. 주변의 도움을 허용한 상태라 여기저기 알아보고 있는데
다들 고개를 흔들고 있습니다. ㅠ.ㅠ
기본적인 소스는 찾았는데... 데드락과 기아 문제를
해결하는 프로그램을 완성해 주실 수 있으신지 문의드립니다.
염치없는 행동이지만...
갓 전역한 복학생의 난감함으로 부탁드립니다.
/* The dining philosopher program. */
#include
#include /* for calloc() and exit() */
#define N 5 /* number of philosophers */
#define Busy_Eating 1
#define Busy_Thinking 1
#define Left(p) (p) /* chopstick macros */
#define Right(p) (((p) + 1) % N)
typedef int * semaphore;
semaphore chopstick[N]; /* global array */
int fork(void);
semaphore make_semaphore(void);
void philosopher(int me);
void pick_up(int me);
int pipe(int pd[2]);
void put_down(int me);
int read(int fd, void *buf, unsigned len);
void signal(semaphore s);
void sleep(unsigned seconds);
void wait(semaphore s);
int write(int fd, void *buf, unsigned len);
int main(void)
{
int i;
for (i = 0; i < N; ++i) { /* put chopsticks on the table */
chopstick[i] = make_semaphore();
signal(chopstick[i]);
}
for (i = 0; i < N - 1; ++i) /* create philosophers */
if (fork() == 0)
break;
philosopher(i); /* all executing concurrently */
return 0;
}
/* Acquire chopsticks, input is philosopher number. */
void pick_up(int me)
{
if (me == 0) {
wait(chopstick[Right(me)]);
printf("Philosopher %d picks up right chopstick\n", me);
sleep(1); /* simulate slow picking up to encourage deadlock */
wait(chopstick[Left(me)]);
printf("Philosopher %d picks up left chopstick\n", me);
}
else {
wait(chopstick[Left(me)]);
printf("Philosopher %d picks up left chopstick\n", me);
sleep(1); /* simulate slow picking up to encourage deadlock */
wait(chopstick[Right(me)]);
printf("Philosopher %d picks up right chopstick\n", me);
}
}
/* Relinquish chopsticks, input is the philosopher number. */
void put_down(int me)
{
signal(chopstick[Left(me)]);
signal(chopstick[Right(me)]);
}
/* Philosopher process, input is the philosopher number. */
void philosopher(int me)
{
char *s;
int i = 1;
for ( ; ; ++i) { /* forever */
pick_up(me);
s = i == 1 ? "st" : i == 2 ? "nd" : i == 3 ? "rd" : "th";
printf("Philosopher %d eating for the %d%s time\n", me, i, s);
sleep(Busy_Eating);
put_down(me);
printf("Philosopher %d thinking\n", me);
sleep(Busy_Thinking);
}
}
semaphore make_semaphore(void)
{
int *sema;
sema = calloc(2, sizeof(int)); /* permanent storage */
pipe(sema);
return sema;
}
void wait(semaphore s)
{
int junk;
if (read(s[0], &junk, 1) <= 0) {
printf("ERROR: wait() failed, check semaphore creation.\n");
exit(1);
}
}
void signal(semaphore s)
{
if (write(s[1], "x", 1) <= 0) {
printf("ERROR: write() failed, check semaphore creation.\n");
exit(1);
}
}
나름대로, 게시물을 지워야 하는지- 답글을 달아드려야 하는지 많이 고민했습니다.
식사하는 철학자 문제는 인터넷상에 자료가 많이 있습니다. 해결책도 덩달아 많이 있구요.
소스코드를 보아하니 님이 말씀하신 문제를 해결한 내용이 포함되어 있습니다.
gcc 로 컴파일 하시고, 실행해 보시겠습니까?