为什么 condition_variable_any 需要一个由 shared_ptr 管理的互斥锁?

Via*_*rus 5 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);
  }
Run Code Online (Sandbox Code Playgroud)

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

vll*_*vll 6

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

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

c11 标准(草案 3337,第 30.5.1.5 段)指出,即使不是所有的 wait() 调用都已返回,条件变量也可能会被破坏,只要所有这些调用都阻塞在相关联的锁上而不是 *this 上。

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