In my endless quest to understand std::contion_variable I came across the following. This page says the following:
void print_id (int id) { std::unique_lock<std::mutex> lck(mtx); while (!ready) cv.wait(lck); // ... std::cout << "thread " << id << '\n'; }
And after that he says this:
void go() { std::unique_lock<std::mutex> lck(mtx); ready = true; cv.notify_all(); }
Now, as I understand it, both of these functions will stop at the line std::unqique_lock . Until a unique castle is found. That is, no other thread has a lock.
So first we say that the print_id function print_id executed. The unique lock will be activated and the function will stop on the standby line.
If the go function is then executed (in a separate thread), the code will stop there on a unique lock line. Since the mutex is locked by the print_id function.
Obviously, this would not work if the code were like that. But I really don't understand what I will not get here. So please enlighten me.
c ++ multithreading locking mutex c ++ 11
laurisvr
source share