Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ std::condition_变量真的在阻塞之前解锁给定的唯一_锁对象吗?_C++_Multithreading_G++_C++17_Condition Variable - Fatal编程技术网

C++ std::condition_变量真的在阻塞之前解锁给定的唯一_锁对象吗?

C++ std::condition_变量真的在阻塞之前解锁给定的唯一_锁对象吗?,c++,multithreading,g++,c++17,condition-variable,C++,Multithreading,G++,C++17,Condition Variable,正如参考文献所说: 我有以下代码: #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_lo

正如参考文献所说:

我有以下代码:

#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;
}
但根据参考资料,我希望在等待时解锁互斥锁,即:

In main, lck.owns_lock() = 0

有人能告诉我为什么会这样吗?

你需要进一步阅读:

解除阻止后,无论原因如何,都会重新获取锁并等待退出。如果此函数通过异常退出,则也会重新获取锁


所以,总是可以保证在退出等待时,会重新获得锁。

但我要问,为什么程序没有观察到同样的情况?输出与参考文档不一致。main中的cout在等待退出之前执行。实际上,代码中存在数据竞争。您正在从两个线程访问
lck
,但
std::unique_lock
不是为此而设计的。很容易检查
mutex\uuu
是否已解锁:尝试在
main
sleep\u之后立即获取
的mutex。
In main, lck.owns_lock() = 0