gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:49:55 25 4
gpt4 key购买 nike

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/

25 4 0