正如引用所言:1) Atomically unlocks lock, blocks the current executing thread, and...
我有以下代码:
#include <iostream>
#include <thread>
#include <condition_variable>
std::mutex mutex_;
std::condition_variable condVar;
std::unique_lock<std::mutex> lck(mutex_); //purposely global to check return of owns_lock() in main
void waitingForWork()
{
std::cout << "Before wait, lck.owns_lock() = " << lck.owns_lock() << '\n';
condVar.wait(lck);
std::cout << "After wait, lck.owns_lock() = " << lck.owns_lock() << '\n';
}
int main()
{
std::thread t1(waitingForWork);
std::this_thread::sleep_for(std::chrono::seconds(10));
std::cout << "In main, lck.owns_lock() = " << lck.owns_lock() << '\n';
condVar.notify_one();
t1.join();
return 0;
}
编译使用:g++ with c++17 on ubuntu
输出:Before wait, lck.owns_lock() = 1
In main, lck.owns_lock() = 1
After wait, lck.owns_lock() = 1
但是根据引用,我希望互斥锁会在等待时被解锁,即:In main, lck.owns_lock() = 0
有人可以告诉我为什么吗?
最佳答案
您必须进一步阅读:
When unblocked, regardless of the reason, lock is reacquired and wait exits. If this function exits via exception, lock is also reacquired.
因此,始终保证在退出等待时重新获得该锁。
关于c++ - std::condition_variable在阻塞之前是否真的解锁了给定的unique_lock对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64452317/