/* * CS560: Operating Systems * Jim Plank * dphil_3.c -- Dining philosophers solution #3 -- grab the sticks with semaphores * 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 #define GOT_SEM_1 3 #define GOT_SEM_2 4 typedef struct { cbthread_gsem *sems; int *my_pstates; } MyPhil; 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_SEM_1; cbthread_gsem_P(m->sems[s1], i_am_hungry, p); } else if (m->my_pstates[p->id] == GOT_SEM_1) { 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_SEM_2; cbthread_gsem_P(m->sems[s2], i_am_hungry, p); } else if (m->my_pstates[p->id] == GOT_SEM_2) { 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) { cbthread_gsem_V(m->sems[s1]); m->my_pstates[p->id] = BEGIN; put_down_stick(p, s2, i_am_sated); } else { cbthread_gsem_V(m->sems[s2]); p->state = STARTING; philosopher(p); cbthread_exit(); } } void initialize_simulation(Simulation *s) { MyPhil *m; int i; m = talloc(MyPhil, 1); m->my_pstates = talloc(int, s->nphil); m->sems = talloc(cbthread_gsem, s->nphil); for (i = 0; i < s->nphil; i++) { m->sems[i] = cbthread_make_gsem(1); m->my_pstates[i] = BEGIN; } s->v = (void *) m; return; }