/* * CS560: Operating Systems * Jim Plank * dphil_5.c -- Dining philosophers solution #5 -- the book's solution * 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 #define BLOCKED 5 typedef struct { cbthread_gsem *sems; int *sticks_free; 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->sticks_free[s1] || !m->sticks_free[s2])) { m->my_pstates[p->id] = BLOCKED; cbthread_gsem_P(m->sems[p->id], i_am_hungry, p); } if (m->my_pstates[p->id] == BEGIN) { m->sticks_free[s1] = 0; m->sticks_free[s2] = 0; 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; int before, after; m = (MyPhil *) p->s->v; s1 = p->id; s2 = (p->id+1)%p->s->nphil; if (m->my_pstates[p->id] == GOT_STICK_2) { /* Put down first stick */ 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) { /* Check the philosopher that shares s1 */ m->sticks_free[s1] = 1; before = (p->id + p->s->nphil - 1) % p->s->nphil; if (m->my_pstates[before] == BLOCKED) { cbthread_gsem_V(m->sems[before]); m->my_pstates[before] = BEGIN; } m->my_pstates[p->id] = BEGIN; /* Put down s2 */ put_down_stick(p, s2, i_am_sated); } else { m->sticks_free[s2] = 1; after = (p->id + 1) % p->s->nphil; /* Check the philosopher that shares s2 */ if (m->my_pstates[after] == BLOCKED) { cbthread_gsem_V(m->sems[after]); m->my_pstates[after] = BEGIN; } 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->sticks_free = talloc(int, s->nphil); m->sems = talloc(cbthread_gsem, s->nphil); for (i = 0; i < s->nphil; i++) { m->sems[i] = cbthread_make_gsem(0); m->my_pstates[i] = BEGIN; m->sticks_free[i] = 1; } s->v = (void *) m; return; }