c++ - 为什么 condition_variable_any 需要一个由 shared_ptr 管理的互斥体?

标签 c++ multithreading mutex resource-management

std::conditional_variable_any 的实现需要(在 gccclang 中)一个 std::shared_ptr。

wait 方法中,互斥锁的生命周期将延长到本地范围。

template<typename _Lock>
  void
  wait(_Lock& __lock)
  {
shared_ptr<mutex> __mutex = _M_mutex; // <-- Extend lifetime of mutex.
unique_lock<mutex> __my_lock(*__mutex);
_Unlock<_Lock> __unlock(__lock);
// *__mutex must be unlocked before re-locking __lock so move
// ownership of *__mutex lock to an object with shorter lifetime.
unique_lock<mutex> __my_lock2(std::move(__my_lock));
_M_cond.wait(__my_lock2);
  }

我想知道,为什么我们在这里需要这个?只要 conditional_variable_any 对象存在,互斥就会存在。一个 std::mutex 还不够吗?

最佳答案

此错误报告中添加了代码:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54352

解释如下:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54185

The c11 standard (draft 3337, paragraph 30.5.1.5) states that condition_variable may be destructed even if not all wait() calls have returned, so long as all of those calls are blocking on the associated lock rather than on *this.

因此必须延长生命周期以防止在互斥量仍在使用时破坏它。

关于c++ - 为什么 condition_variable_any 需要一个由 shared_ptr 管理的互斥体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57053735/

相关文章:

c++ - 为什么在代码块中执行时会跳过输入用户输入的行?

c++ - 为什么类成员的地址与其对象相同?

C# 线程访问 if block ,其条件返回 false

linux - pthread 互斥体解锁如何工作?线程是否同时出现?

c - 在其他线程执行 mutex_unlock() 之后,等待互斥体的线程是否会立即获得所有权?

windows - Windows 上的递归互斥体?

c++ - 整数在 float 中的精确表示

c++ - 为什么在我的光线追踪器中计算阴影和反射时会丢失细节

java线程等待comport上的输入也会阻塞其他线程

Java同步: If more than one methods in java are made atomic/synchronized,锁是同时应用于所有的吗?