我想了解互斥鎖在條件變量中使用時會發生什麼。當調用條件變量的通知時,互斥鎖是否會被解鎖
在以下示例中,從cppreference
int main()
{
std::queue<int> produced_nums;
std::mutex m;
std::condition_variable cond_var;
bool done = false;
bool notified = false;
std::thread producer([&]() {
for (int i = 0; i < 5; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::unique_lock<std::mutex> lock(m);
std::cout << "producing " << i << '\n';
produced_nums.push(i);
notified = true;
cond_var.notify_one();
}
done = true;
cond_var.notify_one();
});
std::thread consumer([&]() {
std::unique_lock<std::mutex> lock(m);
while (!done) {
while (!notified) { // loop to avoid spurious wakeups
cond_var.wait(lock);
}
while (!produced_nums.empty()) {
std::cout << "consuming " << produced_nums.front() << '\n';
produced_nums.pop();
}
notified = false;
}
});
producer.join();
consumer.join();
}
採取的生產者線程調用cond_var.notify_one()互斥被解鎖之前。當通知被調用時互斥鎖m是否被解鎖,或者僅當互斥鎖被解鎖時纔會發生通知?
究竟是在找什麼:D –