Created October 19, 2014 19:07
-
-
Save anonymous/4d218dce2a43a06abe6a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| 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