c++ - std::condition_variable在阻塞之前是否真的解锁了给定的unique_lock对象?

标签 c++ multithreading g++ c++17 condition-variable

正如引用所言: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/

相关文章:

c++ - 多个 if-else 测试的更简单方法

c++ - QTableWidget:信号itemChanged触发得太晚了(在发出其他 Action 的信号,关闭等之后)

java - 一次运行多线程并让线程快速运行?

iPhone:一个对象,一个线程

c# - 为什么 Task.Factory.StartNew() 需要使用 CancellationToken 重载?

java - 从 Java (GCJ) 调用 C++ 代码

c++ - 3rd-party 垃圾收集器中使用的方法

c++ - 我可以在 XCode 4 或 OSX Lion 中使用 C++11 的最新功能吗?

c++ - 为什么一个简单的C++程序会产生这么多分支命令?在 Linux 上使用性能

c++ - 有没有更好的方法使这段代码线程安全? Thread_local static 似乎是一个生硬的工具