Skip to content

Instantly share code, notes, and snippets.

@Fraser999
Created October 16, 2012 16:23
Show Gist options
  • Save Fraser999/3900343 to your computer and use it in GitHub Desktop.
Save Fraser999/3900343 to your computer and use it in GitHub Desktop.
Shows issue relating to invoking boost::condition_variable::notify_all outside of mutex-protected scope
#include <condition_variable>
#include <thread>
#include "boost/thread/condition_variable.hpp"
#include "boost/thread/thread.hpp"
template<typename Thread, typename Lock, typename CondVar>
void Loop() {
for (int i = 0; i < 10000; ++i) {
CondVar condition_variable;
Lock::mutex_type mutex;
bool flag(false);
Lock unique_lock(mutex);
Thread thread([&condition_variable, &mutex, &flag] {
{
Lock lock(mutex);
flag = true;
}
condition_variable.notify_all();
});
thread.detach();
while (!flag) {
printf("Wait %i\n", i);
condition_variable.wait(unique_lock);
}
}
}
int main() {
Loop<std::thread, std::unique_lock<std::mutex>, std::condition_variable>();
Loop<boost::thread, boost::unique_lock<boost::mutex>, boost::condition_variable>();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment