/* * CS560: Operating Systems * Jim Plank * dphil_a.c - Using a hunger threshold * January, 2009 */ #include #include #include "cbthread.h" #include "dphil.h" #include "dllist.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 #define WANTING_STICKS 6 typedef struct { cbthread_gsem *sems; int *sticks_free; int *my_pstates; double *hunger_time; } MyPhil; int test_philosopher(int pid, MyPhil *m, Simulation *s) { int before, after; if (m->my_pstates[pid] != WANTING_STICKS) return 0; after = (pid + 1) % s->nphil; if (!m->sticks_free[pid] || !m->sticks_free[after]) return 0; if (m->my_pstates[after] == WANTING_STICKS && m->hunger_time[pid] - s->eatavg * 10 > m->hunger_time[after]) return 0; before = (pid + s->nphil - 1) % s->nphil; if (m->my_pstates[before] == WANTING_STICKS && m->hunger_time[pid] - s->eatavg * 10 > m->hunger_time[before]) return 0; return 1; } 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->hunger_time[p->id] = cbthread_get_fake_time(); m->my_pstates[p->id] = WANTING_STICKS; } if (test_philosopher(p->id, m, p->s)) { 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] == WANTING_STICKS) { cbthread_gsem_P(m->sems[p->id], i_am_hungry, p); } 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) { 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->sticks_free[s1] = 1; before = (p->id + p->s->nphil - 1) % p->s->nphil; if (test_philosopher(before, m, p->s)) cbthread_gsem_V(m->sems[before]); m->my_pstates[p->id] = BEGIN; put_down_stick(p, s2, i_am_sated); } else { m->sticks_free[s2] = 1; after = (p->id + 1) % p->s->nphil; if (test_philosopher(after, m, p->s)) cbthread_gsem_V(m->sems[after]); 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); m->hunger_time = talloc(double, 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; }