/*****************************************************/
/* Example code from class using the pthread library */
/*                                                   */
/* To compile me in Linux:                           */
/*    gcc -raceexample raceexample.c -lpthread       */
/*                                                   */
/*  This is the solution to the race condition.      */
/*****************************************************/
#include <stdio.h>
#include <pthread.h>

void *runner(void * param);   /* function that the thread will execute */
long int sum;
long int limit=10000000;

pthread_mutex_t mut;

int main() {
  pthread_t tid;
  pthread_attr_t attr;
  int i;

  pthread_mutex_init(&mut, NULL);

  pthread_attr_init(&attr);

  sum=0;
  printf("In main before creating the thread, sum=%ld\n",sum);

  pthread_create( &tid, &attr, runner, NULL);

  for (i=0; i<limit; i++) {
    /* critical section */
    pthread_mutex_lock(&mut);   
    sum++;
    pthread_mutex_unlock(&mut);  
  }

  pthread_join( tid, NULL);  /* makes the main code wait for the thread */

  printf("Main is done, sum=%ld\n", sum);

  return 0;
}

void * runner(void *param)
{
   int i;
   for (i=0; i<limit; i++) {
     /* critical section */
     pthread_mutex_lock(&mut);   
     sum++;  /* protect access to shared memory!!  */
     pthread_mutex_unlock(&mut);  
   }

   pthread_exit(0);
}
  

