In: Computer Science
#include <thread>
#include <iostream>
using namespace std;
const unsigned int NTHREADS = 20;
const int ITERS = 10000000;
int counter;
void increment()
{
for (int i = 0; i < ITERS; i++)
counter++;
}
void decrement()
{
for (int i = 0; i<ITERS; i++)
counter--;
}
int main()
{
cout << "The counter is " << counter << endl;
thread *threads = new thread[NTHREADS];
for (unsigned int i = 0; i<NTHREADS; i++)
if (i % 2 == 0)
threads[i] = thread(increment);
else
threads[i] = thread(decrement);
for (unsigned int i = 0; i<NTHREADS; i++)
threads[i].join();
cout << "The counter is " << counter << endl;
return 0;
}
A mutex (mutual exlusion) allows us to encapsulate blocks of code that should only be executed in one thread at a time.
Apply mutex to solve the issue in the previous code. Show your revised code and running result.