#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 synchronization. 
 *
 * On every fourth loop the master sends a signal to the slave and the
 * slave will loop ones and print PANG. The master writes ping in all
 * loops.
 *
 * Compilation at linux:   gcc -lpthread -lrt pthread2.c -o pthread2
 * Compilation at solaris: gcc -lpthread -lrt pthread2.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 (;;)
    {
      printf("ping\n");
      i++;
      if (i==3) 
	{
	  i=0;
	  sem_post(&sem1);
	  sleep(1);
	}
    }
}

void * thread_slave(void * aparm)
{
  int i,j;
  j = (int)aparm;
  for (;;)
    {
      sem_wait(&sem1);
      printf("PANG\n");

    }
}

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");

  /* 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 */

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

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