#include <stdio.h>
#include <pthread.h>

#define NTHREADS 2
void *phil();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;


main()
{
  pthread_t thread_id[NTHREADS];
  int i, j;

  for(i=0; i < NTHREADS; i++)
    {
      pthread_create( &thread_id[i], NULL, &phil, NULL );
    }

  for(j=0; j < NTHREADS; j++)
    {
      pthread_join( thread_id[j], NULL); 
    }
  
  /* Now that all threads are complete I can print the final result.     */
  /* Without the join I could be printing a value before all the threads */
  /* have been completed.                                                */

}

void *phil()
{
  int i;
  int count = 0;
  i = pthread_self();
  while (1) {
    printf("phil id: %d enter loop no %d \n", i, count);
    sleeping(i);

    pthread_mutex_lock( &mutex1 );
    drinking(i);
    pthread_mutex_unlock( &mutex1 );
    if (count++ == 3) break;
  }
}

void sleeping(int i) {
  unsigned int howlong;

  howlong = (rand() % 10);
  printf("phil id: %d enter sleep\n", i);

  sleep(howlong);
}

void drinking(int i) {
  unsigned int hl;

  hl = (rand() % 10);

  printf("phil id: %d enter eat\n", i);
  sleep(hl);

}
