【问题标题】:Why does condition_variable_any needs a mutex managed by a shared_ptr?为什么 condition_variable_any 需要由 shared_ptr 管理的互斥锁?
【发布时间】:2019-11-24 23:34:16
【问题描述】:

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 还不够吗?

【问题讨论】:

    标签: c++ multithreading mutex resource-management


    【解决方案1】:

    此错误报告中添加了代码: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 .

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 2011-02-15
      • 2015-05-20
      相关资源
      最近更新 更多