/* 
   This file is part of Practical Distributed Processing
   Copyright (C) 2006-2007 Phillip J. Brooke and Richard F. Paige
*/

#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
#define DELAY 100000L
#define DICT_SIZE 1024

int main() {
   char* dictionary[DICT_SIZE];
   int counter = 0;
   int tmp;
   sem_t semaph;
   struct timespec delaytime;
   
   /* Set up sleep period for output */
   delaytime.tv_sec = 0;
   delaytime.tv_nsec = DELAY;

   /* Create a semaphore */
   tmp = sem_init( &semaph, 0, 1 ); 

   /* Initialise dictionary */
   while(counter < DICT_SIZE){
     dictionary[counter] = "Test";
     counter++;
   }

   counter = 0;

   /* Entry to critical region */
   while (sem_wait(&semaph) == -1)  {    
      if(errno != EINTR) {
         fprintf(stderr, "Locking of semaphore failed\n");
         return 1;
      }
   }

   /* Critical region */
   while (counter < DICT_SIZE) {
      fprintf(stdout, dictionary[counter]);
      counter++;
      nanosleep(&delaytime, NULL);
   }
   /* End of critical region */

   /* Exit from critical region */
   if (sem_post(&semaph) == -1)     
      fprintf(stderr, "Unlocking of semaphore failed\n");

   return 1;
}
