On my neverending quest to understand std::contion_variable
s I've run into the following. On this page it says the following:
void print_id (int id) {
std::unique_lock<std::mutex> lck(mtx);
while (!ready) cv.wait(lck);
// ...
std::cout << "thread " << id << '
';
}
And after that it 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 halt on the std::unqique_lock
line. Until a unique lock is acquired. That is, no other thread has a lock.
So say the print_id
function is executed first. The unique lock will be aquired and the function will halt on the wait line.
If the go
function is then executed (on a separate thread), the code there will halt on the unique lock line. Since the mutex is locked by the print_id
function already.
Obviously this wouldn't work if the code was like that. But I really don't see what I'm not getting here. So please enlighten me.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…