/* * CS560: Operating Systems * Jim Plank * dphil_2.c -- Dining philosophers solution #2 -- just grab those sticks!! * January, 2009 */ #include #include #include "cbthread.h" #include "dphil.h" #define talloc(ty, sz) (ty *) malloc ((sz) * sizeof(ty)) #define BEGIN 0 #define GOT_STICK_1 1 #define GOT_STICK_2 2 typedef struct { int *my_pstates; } MyPhil; void initialize_simulation(Simulation *s) { MyPhil *m; int i; m = talloc(MyPhil, 1); m->my_pstates = talloc(int, s->nphil); for (i = 0; i < s->nphil; i++) { m->my_pstates[i] = BEGIN; } s->v = (void *) m; return; } void i_am_hungry(Philosopher *p) { MyPhil *m; int s1, s2; m = (MyPhil *) p->s->v; s1 = p->id; s2 = (p->id+1)%p->s->nphil; if (m->my_pstates[p->id] == BEGIN) { m->my_pstates[p->id] = GOT_STICK_1; pick_up_stick(p, s1, i_am_hungry); } else if (m->my_pstates[p->id] == GOT_STICK_1) { m->my_pstates[p->id] = GOT_STICK_2; pick_up_stick(p, s2, i_am_hungry); } else { p->state = GOTSTICKS; philosopher(p); cbthread_exit(); } } void i_am_sated(Philosopher *p) { MyPhil *m; int s1, s2; m = (MyPhil *) p->s->v; s1 = p->id; s2 = (p->id+1)%p->s->nphil; if (m->my_pstates[p->id] == GOT_STICK_2) { m->my_pstates[p->id] = GOT_STICK_1; put_down_stick(p, s1, i_am_sated); } else if (m->my_pstates[p->id] == GOT_STICK_1) { m->my_pstates[p->id] = BEGIN; put_down_stick(p, s2, i_am_sated); } else { p->state = STARTING; philosopher(p); cbthread_exit(); } }