Exemplo n.º 1
0
void think(unsigned int myID){
	int currentThink = randomGaussian_r(11, 7, &seed[myID]);
	if (currentThink < 0) currentThink = 0;
	printf("(think) Philo %d is thinking for %d seconds.\n", myID, currentThink);
	fflush(stdout);
	sleep(currentThink);
	return;
}
Exemplo n.º 2
0
int eat(unsigned int myID){
	int currentEat = randomGaussian_r(9, 3, &seed[myID]);
	if (currentEat< 0) currentEat = 0;
	printf("(eat) Philo %d is eating for %d seconds.\n", myID, currentEat);
	fflush(stdout);
	sleep(currentEat);
	return currentEat;
}
Exemplo n.º 3
0
// This function simulates the philosophers eating and thinking.
void* philosopher(void* arg){  

  int philo =   *((int*) arg);
  int eatingTime = 0;
  int totalEatingTime = 0;
  int thinkingTime = 0;
  int totalThinkingTime =0;
  free(arg);
  unsigned int state = philo;

  while(totalEatingTime <= MAX_EATING_TIME){
    // try to acquire chopsticks if available.
    while (1) {
    	pthread_mutex_lock(&chopstiks[philo]);
    	int rtrn = pthread_mutex_trylock(&chopstiks[(philo+1) % 5]);
    
    	if (rtrn == EBUSY)
    		pthread_mutex_unlock(&chopstiks[philo]);
    	else break;
    	sleep(1);
    }
    	
   	/******* philosopher i is eating for a random amount of time.*******/
    if((eatingTime = randomGaussian_r(EATING_MEAN, EATING_STD, &state)) < 0)
    	eatingTime = 0;

	eating(philo, eatingTime, totalEatingTime);
    totalEatingTime += eatingTime;
   	 
    // done eating, Release the chopsticks.
    pthread_mutex_unlock(&chopstiks[philo]);
	pthread_mutex_unlock(&chopstiks[(philo+1) % 5]);

   	 /****** Philo is thinking for a random amount of time. ********/
   	if((thinkingTime = randomGaussian_r(THINKING_MEAN, THINKING_STD, &state)) < 0) 
    	thinkingTime = 0;
	totalThinkingTime += thinkingTime;
 	thinking(philo, thinkingTime, totalThinkingTime);  
  } 
  printf("Philo %i has finished eating. [Total time spent eating = %i]\n", philo, totalEatingTime);
  philoTimeEating[philo] = totalEatingTime;
  philoTimeThinking[philo] = totalThinkingTime;
  return NULL;
}