#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
pthread_t t1,t2;  /* thread process descriptor */

sem_t sem1;

int i1,i2;

/**
 * Create two threads and do a mutual exclusion. The master thread will only
 * enter the locked region is it is available
 *
 * Variants of sema calls
 *
 * NB NB remember -lrt
 *
 * A critical region
 *
 * Compilation at linux:   gcc -lpthread -lrt pthread5.c -o pthread2
 * Compilation at solaris: gcc -lpthread -lrt pthread5.c -o pthread2
 * exe file will be pthread 1 or 2
 */

void * thread_master(void * aparm)
{
  int i,j;
  j = (int)aparm;
  i = 0;
  for (;;)
    {
      /* get the lock if it is vacant - otherwise ignore */
      if (0 ==sem_trywait(&sem1)) 
	{
	  
      printf("MASTER I am on the screen alone !!! \n");
      sem_post(&sem1);
    }
      else 
	{
	  printf("Maser did not ge screen - and this writing is ...");
	}
    }
}

void * thread_slave(void * aparm)
{
  int i,j;
  j = (int)aparm;
  for (;;)
    {
      sem_wait(&sem1);
      printf("I on the screen alone !!! \n");
      sleep(2);
      printf("SLAVE did sleep 2 seconds when locking the screen\n");
      sem_post(&sem1);

    }
}

int main(int argc, char *argv[])
{
  int i;
  int res;
  printf("\nHello out there\n");
  printf("I have been called with %i parms\n", argc);

  printf("creating a thread NOW\n");

  sem_init(&sem1,0,1); /* startvalue 1 */

  /* create thread nr 1 and and transfer "1" to the thread */
  res = pthread_create(&t1,NULL,thread_master,(void *)1);

  /* create thread nr 1 and and transfer "2" to the thread */
  res = pthread_create(&t2,NULL,thread_slave,(void *)2);

  /* create a semaphore for mutual exclusion */


  for (i=0;i<argc;i++) 
  {
    printf("arg %i: %s\n",i,argv[i]);
  }
  sleep(10);
}
