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++ - 如何修复 "defined in discarded section"链接器错误?

c++ - Boost 1.53 本地日期时间编译器错误 -std=c++0x

c++ - 如何检查 char* p 是否到达 C 字符串的末尾?

java - 线程的 String 字段上的 getter 和 setter 是否必须同步/

c++ - 为什么这个初始化本身不会产生编译器警告?

Java 线程问题,处理程序消息数据被下一条消息覆盖

java - Linux 系统上使用 Java/Eclipse TPTP 进行 16 线程/16 核心代码分析

c++ - 链接器错误 : _main already defined in *. obj

python - 从文件中提取与另一个文件中的条件匹配的某些行

c++ - 按需条件 std::atomic_thread_fence 获取的优缺点?