//E.g. with mutex - Global variable is updated by 1, 10,000 times by each thread
 
#include <pthread.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

pthread_mutex_t cntr_mutex;  //declaration of mutex
#define MAX_THREADS  10

int protVariable = 0; //global that is shared by all threads

//Each thread does the following
void *myThread( void *arg ){
  int i, ret;

  for (i = 0 ; i < 10000 ; i++) {
    //acquire lock
    ret = pthread_mutex_lock( &cntr_mutex );

    //If successful go an update the global variable 
    assert( ret == 0 );

    protVariable++;

    //give up mutex as your done with critcal section
    ret = pthread_mutex_unlock( &cntr_mutex );

    assert( ret == 0 );

  }

  pthread_exit( NULL );
}


int main()
{
  int ret, i;
  pthread_t threadIds[MAX_THREADS]; 

  pthread_mutex_init(&cntr_mutex, NULL); //set up mutex

  for (i = 0 ; i < MAX_THREADS ; i++) {
    ret = pthread_create( &threadIds[i], NULL, myThread, NULL );
    if (ret != 0) {
      printf( "Error creating thread %d\n", (int)threadIds[i] );
      exit(-1);
    }
  }

  for (i = 0 ; i < MAX_THREADS ; i++) {
    ret = pthread_join( threadIds[i], NULL );
    if (ret != 0) {
      printf( "Error joining thread %d\n", (int)threadIds[i] );
      exit(-1);
    }
  }

  printf( "The protected variable value is %d\n", protVariable );

  ret = pthread_mutex_destroy( &cntr_mutex );

  if (ret != 0) {
    printf( "Couldn't destroy the mutex\n");
    exit(-1);
  }

  return 0;  
}


