C++ 如何在锁定条件变量后运行函数?

C++ 如何在锁定条件变量后运行函数?,c++,c++11,locking,conditional-statements,mutex,C++,C++11,Locking,Conditional Statements,Mutex,为Future变量get\u value()方法提供以下函数体: // Optimization once _is_resolved is set true, we do not need lock anymore if( _is_resolved ) { return _value; } // If _is_resolved is not set to true, lock and double check _is_resolved _lock.lock(); if(!_is_res

Future
变量
get\u value()
方法提供以下函数体:

// Optimization once _is_resolved is set true, we do not need lock anymore
if( _is_resolved ) {
    return _value;
}

// If _is_resolved is not set to true, lock and double check _is_resolved
_lock.lock();
if(!_is_resolved) {
    ++_size;
    std::unique_lock<std::mutex> lock(_mutex);

    // We cannot call _lock.unlock(); before _condition.wait(lock); because
    // 1. It would allow this thread to be preempted
    // 2. Then, some other thread could call resolve()
    // Once this other thread completes the resolve() call, and this
    // thread is rescheduled, we would finally call _condition.wait(lock);
    // but doing so, would cause this thread to be locked indefinitely
    // because we will never call resolve() anymore
    _condition.wait(lock); // How to call _lock.unlock(); after locking?
}
else {
    _lock.unlock();
}
return _value;
调用
wait(lock)
释放
lock
。这里的问题是代码有两个互斥体;就我看来,一个就足够了。它可能不需要是递归的。这通常是设计问题的迹象

我建议删除
\u锁
并坚持使用
\u互斥锁
。然后更改代码,使其如下所示:

if (_is_resolved)
    return _value;
std::unique_lock<std::mutex> lock(_mutex);
if (!_is_resolved) {
    ++_size;
    _condition.wait(lock);
}
return _value;
if(\u已\u解析)
返回_值;
std::唯一的锁(互斥锁);
如果(!\u已解决){
++_大小;
_条件。等待(锁定);
}
返回_值;

请查看文档。这并没有解决这个问题,但我认为这里不需要两个互斥体,也不需要任何一个是递归的。像这样编写代码的通常方法是使用一个互斥锁;使用
唯一锁将其锁定(在代码调用
\u lock.lock()
的位置,移除内部
唯一锁
,并移除对
\u lock.unlock()
的调用。谢谢@PeteBecker,它修复了它!您可以将其作为答案发布吗?
if (_is_resolved)
    return _value;
std::unique_lock<std::mutex> lock(_mutex);
if (!_is_resolved) {
    ++_size;
    _condition.wait(lock);
}
return _value;