Thread Synchronization in C++11
1. Tried condition_variable to signal from one to another. Something like one of sync objects (event, mutex, critial section, …) and WaitForSingleObject() in Windows. Lambda in the cond.wait() was called twice. How should I remove the 1st call by creating unsignaled cond?
code:
mutex mtx; condition_variable cond; bool done = false; thread t = thread([&]() { // define _GLIBCXX_USE_NANOSLEEP this_thread::sleep_for(chrono::seconds(2)); cout << "[" << this_thread::get_id() << "] notifying" << endl; done = true; cond.notify_one(); }); thread t2 = thread([&]() { cout << "[" << this_thread::get_id() << "] waiting..." << endl; unique_lock<mutex> lock(mtx); cond.wait(lock, [&]() { cout << "[" << this_thread::get_id() << "] notified. done=" << done << endl; return done == true; }); }); t.join(); t2.join(); cout << "all done" << endl;
output:
[0x105bcb000] waiting... [0x105bcb000] notified. done=0 [0x105b48000] notifying [0x105bcb000] notified. done=1 all done
2. Borrowed rendezvous from here to suspend all threads until specified number of threads call wait(), then resume running them.
code:
const int numThreads = 10; rendezvous r(numThreads + 1); mutex mtx; vector<thread> threads(numThreads); for (int i : range(0, numThreads)) { threads[i] = thread([&]() { this_thread::sleep_for(chrono::seconds(2)); { lock_guard<mutex> guard(mtx); // just to synchronize print output cout << "[" << this_thread::get_id() << "] done" << endl; } r.wait(); }); } r.wait(); cout << "all done" << endl; for (int i : range(0, numThreads)) { threads[i].join(); }
output:
[0x10a83c000] done [0x10a942000] done [0x10a8bf000] done [0x10a9c5000] done [0x10aa48000] done [0x10aacb000] done [0x10ab4e000] done [0x10abd1000] done [0x10a736000] done [0x10a7b9000] done all done