/*
 * Let two threads access the same variable 'total' and guard mutually
 * exclusive access with a mutex.
 *
 * Alternative approach for accessing just one variable:
 *   take a look at C++11 atomic operations.
 */

#include <iostream>
#include <mutex>
#include <thread>


std::mutex totalmutex; // mutually exclusive guard for total

int total=0; // the shared resource we want to protect
int nrOfIterations=100000;

void job_1()
{
  for(int i=0; i<nrOfIterations; i++){
    totalmutex.lock();
    total++;
    totalmutex.unlock();
  }
} // job_1()


void job_2()
{
  for(int i=0; i<nrOfIterations; i++){
    totalmutex.lock();
    total--;
    totalmutex.unlock();
  }
} // 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()

