Last active
January 6, 2016 23:11
-
-
Save haampie/17ce3008c6127ad05e88 to your computer and use it in GitHub Desktop.
locks 'n stuff
This file contains 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
#include <condition_variable> | |
#include <iomanip> | |
#include <iostream> | |
#include <thread> | |
using namespace std; | |
int someNumber = 0; | |
mutex numberMutex; | |
condition_variable cv; | |
void waitFunction() | |
{ | |
unique_lock<mutex> lock(numberMutex); | |
auto duration = chrono::seconds(5); | |
// Predicate is only called once? | |
cv.wait_for(lock, duration, []() { | |
cout << "Checking condition: 10 == " << someNumber << '\n'; | |
return someNumber == 10; | |
}); | |
cout << "Done with this thread...\n" << flush; | |
} | |
int main() | |
{ | |
thread waiter(waitFunction); | |
for (size_t number = 0; number != 50; ++number) | |
{ | |
{ | |
lock_guard<mutex> guard(numberMutex); | |
someNumber = number; | |
} | |
cv.notify_one(); | |
} | |
waiter.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Makefile: