/*
 * Let two threads access the same variable 'total' without protecting this
 *  shared resource with e.g. a mutex
 *
 * Thread 1 using job_1 increments the shared variable 'total' exactly as
 *  many times as thread2 using job_2 decrements it, so the end result
 *  should always be 0 but due to simultaneous access it probably isn't
 *
 */

#include <iostream>
#include <thread>


int total=0;
int nrOfIterations=100000;

void job_1() // the increment function
{
  for(int i=0; i<nrOfIterations; i++){
    total++;
  }
} // job_1()


void job_2() // the decrement function
{
  for(int i=0; i<nrOfIterations; i++){
    total--;
  }
} // job_2()


int main()
{
  // Create two threads that execute their own functions
  std::thread thread_1(job_1);
  std::thread thread_2(job_2);

  // join the threads, effectively waiting till both are finished
  thread_1.join();
  thread_2.join();

  // When both threads are finished, show the end result
  std::cout << "Grand total: " << total << std::endl;
} // main()

