/******************************************************************************
* FILE: raceexample-solution-omp.c
* Author:  Amy Apon
*
*  This program fixes the error in the race condition example. 
******************************************************************************/
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

#define LIMIT 1000000

int main (int argc, char *argv[]) {

int nthreads, tid, i, sum=0;

/* Fork a team of threads giving them their own copies of variables */
#pragma omp parallel private(nthreads,tid,i) shared(sum)
  {

  /* Obtain thread number */
  tid = omp_get_thread_num();
  printf("Hello World from thread = %d\n", tid);

  /* Only master thread does this */
  if (tid == 0) 
    {
    nthreads = omp_get_num_threads();
    printf("Number of threads = %d\n", nthreads);
    }
   /* this is protected access to a shared variable using a critical section */
    for (i=0; i<LIMIT; i++) {
#pragma omp critical
       {
	sum++;
       }
/*	if (i%10000==0) printf("Thread %d here, sum=%d\n", tid, sum); */
    }
  
#pragma omp barrier 
  printf("Hello World from thread = %d, sum = %d\n", tid, sum);

  }  /* All threads join master thread and disband */

}


