#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>


/* The global variable on which we have a horrendous
   race condition */
int counter=0;

/* Function for threads to do their thing */
void *do_work(void *arg);

int main(int argc, char **argv) {
  pthread_t worker_thread1;
  pthread_t worker_thread2;
  
  /* Create first worker thread */
  if (pthread_create(&worker_thread1, NULL, 
                     do_work, (void *)1)) {
    fprintf(stderr,"Error while creating thread\n");
    exit(1);
  }

  /* Create second worker thread */
  if (pthread_create(&worker_thread2, NULL, 
                     do_work, (void *)2)) {
    fprintf(stderr,"Error while creating thread\n");
    exit(1);
  }


  /* Waiting for first worker thread */
  if (pthread_join(worker_thread1, NULL)) {
    fprintf(stderr,"Error while joining with thread\n");
    exit(1);
  }

  /* Waiting for second worker thread */
  if (pthread_join(worker_thread2, NULL)) {
    fprintf(stderr,"Error while joining withchild thread\n");
    exit(1);
  }

  /* Print the counter. A value of 0 corresponds to a valid
     execution */
  fprintf(stderr,"After both threads return, counter = %d\n",counter);

  exit(0); 
}

/* The number of iterations for each thread */
#define NUM_ITERATIONS 100000

void *do_work(void *arg) {
  int id = (int)arg;
  int i;
 
  if (id == 1) {  // first thread does counter++
    for (i=0; i < NUM_ITERATIONS; i++) 
      counter++;
  } else { // second thread does counter--
    for (i=0; i < NUM_ITERATIONS; i++) 
      counter--;
  }

  return NULL;
}

