#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono_literals;
condition_variable cv;
mutex mu;
void thread1()
{
mu.lock();
unique_lock lck(mu);
cv.wait(lck);
cout << 1;
}
void thread2()
{
this_thread::sleep_for(1s);
mu.lock();
cv.notify_all();
cout << 2;
}
int main()
{
thread t1(thread1);
thread t2(thread2);
this_thread::sleep_for(2s);
}
This code was expected to show number 1 and 2, but shows nothing.
If a condition variable has waited with a mutex, then the mutex is unlocked, right?
thread2may lock mutex first and raise notify to nowhere.sleep(1)is absolutely wrongly used as a synchronization point.sleep(2)is absolutely wrong too. You get a program terminate. Uset1.join()andt2.join(). See the proper usage example: std::condition_variablemu.lock()without any correspondingmu.unlock(), which leads to problems. Get rid of your explicit calls tomu.lock(), and add aunique_lock<mutex> lck(mu);line tothread2(). Also addt1.join(); t2.join()to the end ofmain()to guarantee that your program won't exit before the threads do.