I've read from https://en.cppreference.com/w/cpp/thread/condition_variable/wait that wait()
"Atomically unlocks lock". How do I see this via std::cout
? I am trying to understand conditional variables better on what they're actually doing. I've wrote an attempt below.
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
condition_variable cv;
mutex m;
bool stopped = false;
void f1() {
unique_lock<mutex> ul{m};
cout << "f1: " << ul.owns_lock() << endl;
cv.wait(ul, [&]{
cout << "f1: " << ul.owns_lock() << endl;
return stopped;
});
cout << "f1 RUNNING\n";
cout << "f1: " << ul.owns_lock() << endl;
}
void f2() {
lock_guard<mutex> lg{m};
cout << "f2 RUNNING\n";
}
int main() {
unique_lock<mutex> ul{m};
thread t1(&f1);
thread t2(&f2);
cout << ul.owns_lock() << endl;
this_thread::sleep_for(chrono::seconds(1));
stopped = true;
cv.notify_one();
cout << ul.owns_lock() << endl;
ul.unlock();
cout << ul.owns_lock() << endl;
this_thread::sleep_for(chrono::seconds(1));
t1.join();
t2.join();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire