【发布时间】:2020-10-20 19:44:14
【问题描述】:
正如参考所说: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
谁能告诉我为什么会这样?
【问题讨论】:
标签: c++ multithreading g++ c++17 condition-variable