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

#define NUM_ROUNDS 500000

/* ---------------------------------------------------------------------- */

void *thread0();
void *thread1();

/* Shared variable updated by both threads */
int accumulator = 0;

/* Shared variables for Peterson's algorithm */
int request_0 = 0;      
int request_1 = 0;
int turn = 0;      

/* ---------------------------------------------------------------------- */

int main(int argc, char *argv[]) {
  pthread_t thread[2];

  /* Start two threads in parallel */
  pthread_create(&thread[0], NULL, thread0, NULL);
  pthread_create(&thread[1], NULL, thread1, NULL);

  /* Wait for both threads to complete */
  pthread_join(thread[0],NULL);
  pthread_join(thread[1],NULL);

  /* Report effect */
  printf("Value of accumulator after %d increments = %d\n", 2*NUM_ROUNDS, accumulator);

}

/* ---------------------------------------------------------------------- */

void *thread0() {
  int i = 0;
  while (i++ < NUM_ROUNDS) {
    request_0 = 1;
    turn = 1;
    while (request_1 && turn != 0) ; /* Busy wait */
    accumulator++;
    request_0 = 0;
  }
}

/* ---------------------------------------------------------------------- */

void *thread1() {
  int i = 0;
  while (i++ < NUM_ROUNDS) {
    request_1 = 1;
    turn = 0;
    while (request_0 && turn != 1) ; /* Busy wait */
    accumulator++;
    request_1 = 0;
  }
}

/* ---------------------------------------------------------------------- */
