Skip to content

Instantly share code, notes, and snippets.

@toddlipcon
Created April 24, 2014 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toddlipcon/11237660 to your computer and use it in GitHub Desktop.
Save toddlipcon/11237660 to your computer and use it in GitHub Desktop.
#include <boost/thread/thread.hpp>
#define CHECK(x) if (!x) { abort(); }
struct State {
State()
: x(0) {
}
boost::mutex m;
boost::condition_variable c;
int x;
};
void Notifier(State* s) {
for (int i = 0; i <= 10000; i++) {
boost::unique_lock<boost::mutex> l(s->m);
s->x = i;
s->c.notify_one();
}
}
int main(int argc, char** argv) {
State s;
boost::thread n(&Notifier, &s);
boost::unique_lock<boost::mutex> l(s.m);
while (s.x < 10000) {
int old_val = s.x;
if (s.c.timed_wait(l, boost::posix_time::microseconds(1))) {
// Return true, we should assume that old_val incremented
CHECK(s.x > old_val);
} else {
// Timed out waiting on notify, so must not have incred
CHECK(s.x == old_val);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment