diner.C
上传用户:shtangtang
上传日期:2007-01-04
资源大小:167k
文件大小:1k
- //
- // This is a philosopher demo, using process scoping.
- #include <thread.h>
- #define MAX_PHILOSOPHERS 5
- int main()
- {
- mutex *p_fork;
- semaphore *sem;
- bool fork_v = false;
- int lfork, rfork, _nr, _forks = MAX_PHILOSOPHERS, _count;
-
- pthread::set_project( "/tmp/philosophy" );
- sem = new semaphore(attributes::process_shared);
- p_fork = new mutex[MAX_PHILOSOPHERS](attributes::process_shared);
- if ( (_nr = sem->post()) > MAX_PHILOSOPHERS ) {
- sem->trywait();
- exit(0);
- }
- _count = _forks;
- _nr -= 1;
- 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 (p_fork[lfork].trylock() == 0) {
- if (p_fork[rfork].trylock() == 0)
- fork_v = true;
- else
- p_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);
- p_fork[lfork].unlock();
- p_fork[rfork].unlock();
- sleep(2);
- }
- cout << _nr << " has finished dining." << endl;
- sem->trywait();
- return 0;
- }