Universidad de Costa Rica

Escuela de Ciencias de la Computación e Informática

CI-0122 Sistemas operativos

Ejemplos

CI0122 / Ejemplos / pthreads / DiningPhilosophers


// Compile with g++ philopt.cc diningph.cc synch.cc -lpthread
// Unix
//
#include <cstdlib>
#include <iostream>
#include <unistd.h>
#include "dinningph.h"

using namespace std;

#define NUMTHRDS 5
int status;
pthread_t thds[NUMTHRDS];

DiningPh * dp;
Mutex * mutex;


int main ( int argc, char *argv[] );
void * Philo ( void *arg );


int main ( int argc, char *argv[] ) {

  int i;

  mutex = new Mutex;
  dp = new DiningPh();

  pthread_attr_t attr;
  pthread_attr_init ( &attr );
  pthread_attr_setdetachstate ( &attr, PTHREAD_CREATE_JOINABLE );

  for ( i = 0; i < NUMTHRDS; i++ ) {
    pthread_create ( &thds[i], &attr, Philo, ( void * ) i );
  }

  pthread_attr_destroy ( &attr );

  for ( i = 0; i < NUMTHRDS; i++ ) {
    pthread_join ( thds[i], ( void ** ) &status );
  }

//  pthread_exit ( NULL );

  cout << "\n";
  cout << "  Normal end of execution.\n";

  return 0;
}


void * Philo( void * p ) {

    int eats, thinks;
    long who = (long) p;

    for ( int i = 0; i < 10; i++ ) {

        mutex->Lock();
        cout << "Round " << i << " philo # " << who + 1 << endl;
        dp->print();
        cout << " Philosopher " << who + 1 << " will try to pickup sticks" << endl;
        mutex->Unlock();

        dp->pickup( who );
        eats = rand() % 6;
        sleep( eats );

        dp->putdown( who );
        thinks = rand() % 6;
        sleep( thinks );
    }

   pthread_exit ( ( void * ) 0 );

}