philosopher.C
上传用户:shtangtang
上传日期:2007-01-04
资源大小:167k
文件大小:1k
- #include "philosopher.h"
- philosopher::philosopher(int n, int forks, void *arg)
- : pthread(arg)
- {
- _nr = n;
- _forks = forks;
- _count = forks;
- }
- philosopher::~philosopher()
- {
- delete p_fork;
- }
- int philosopher::thread(void *ptr)
- {
- bool fork_v = false;
- int lfork, rfork;
-
- application = (dining *)ptr;
- lfork = _nr-1 >= 0 ? _nr-1 : _forks-1;
- rfork = lfork+1 >= _forks ? 0 : lfork+1;
- while(_count-- > 0) {
- cout.form("Philosopher %d: looking for %d,%dn", _nr, lfork, rfork);
- while( fork_v == false ) {
- if (application->fork(lfork).trylock() == 0) {
- if (application->fork(rfork).trylock() == 0)
- fork_v = true;
- else
- application->fork(lfork).unlock();
- }
- }
- cout.form("Philosopher %d: using (%d,%d).n", _nr, lfork, rfork);
- sleep(2);
- fork_v = false;
- cout.form("Philosopher %d: sleepingn", _nr);
- application->fork(lfork).unlock();
- application->fork(rfork).unlock();
- sleep(2);
- }
- application->finished();
- cout << _nr << " has finished dining." << endl;
- return 0;
- }