Skip to content

Instantly share code, notes, and snippets.

Created October 19, 2014 19:07
Show Gist options
  • Select an option

  • Save anonymous/4d218dce2a43a06abe6a to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/4d218dce2a43a06abe6a to your computer and use it in GitHub Desktop.
class LockedIncrement
{
int _nofIncrements;
int _counter;
static std::mutex mtx;
static void increment(int *x, int nofIncrements)
{
for (int i = 0; i < nofIncrements; i++)
{
mtx.lock();
(*x)++;
mtx.unlock();
}
}
public:
LockedIncrement(int nofIncrements)
{
_nofIncrements = nofIncrements;
}
void DoTest()
{
std::thread t1(increment, &_counter, _nofIncrements);
std::thread t2(increment, &_counter, _nofIncrements);
t1.join();
t2.join();
std::cout << "Counter = " << _counter << " (expected " << 2 * _nofIncrements << ")\n";
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment