为什么 condition_variable_any 需要一个由 shared_ptr 管理的互斥量?
Why does condition_variable_any needs a mutex managed by a shared_ptr?
std::conditional_variable_any 的实现需要(在 gcc and clang 中)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.
因此必须延长生命周期以防止在互斥体仍在使用时破坏它。
std::conditional_variable_any 的实现需要(在 gcc and clang 中)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.
因此必须延长生命周期以防止在互斥体仍在使用时破坏它。