c++ - Boost::Future 延迟延续展开死锁

标签 c++ c++11 boost promise deadlock

我正在使用 Boost 的 promisefuture 并在使用延续时遇到了边缘情况。我的代码使用一个返回 future 的延续,并在获取其值之前解包 then() 的结果。

#define BOOST_THREAD_VERSION 5

#include <iostream>
#include <boost/thread/future.hpp>

int main(int argc, char* argv[])
{
    boost::promise<int> promise;
    boost::future<int> future = promise.get_future();

    promise.set_value(42);

    int result = future.then(
        boost::launch::async,
        [](boost::future<int> result)
        {
            return boost::make_ready_future(result.get());
        }
    ).unwrap().get();

    std::cout << "Result is: " << result << std::endl;
    return 0;
}

在此示例中,我明确使用了 boost::launch::async 策略在新线程中启动延续,我得到了预期结果 42。

但是,一旦我用 boost::launch::deferred 替换该策略,程序似乎就会死锁。我做错了什么?

注意:只要我不 unwrap() 它的值,延迟延续就可以正常工作。该问题特别与未包装的延迟延续有关。

最佳答案

我认为 future continuation 与 unwrap 搭配使用没有意义。如果您使用 .then 创建一个 future ,您将获得一个有效的 future 。所以你可以调用 .get() 而不会阻塞。这就是为什么我不认为需要嵌套的 future 。但是,您编写它的方式不应该导致死锁,它可能是一个错误。

#define BOOST_THREAD_VERSION 5

#include <iostream>
#include <boost/thread/future.hpp>

int main(int argc, char* argv[])
{
    boost::promise<int> promise;
    boost::future<int> future = promise.get_future();

    promise.set_value(42);

    int result = future.then(
        boost::launch::deferred,
        [](boost::future<int> result)
        {
            return result.get(); // get is non-blocking, since it is a continuation
        }
    )/*.unwrap()*/.get();

    std::cout << "Result is: " << result << std::endl;
    return 0;
}

从 boost 1.64 开始,unwrap 仍然是一个实验性函数。如果您将此行为传达给 boost::thread 的开发人员,那就太好了。

关于c++ - Boost::Future 延迟延续展开死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44748568/

相关文章:

c++ - cygwin cmake 找不到 boost 库

c++ - 用 "pure"C++11 替代方案替换 BGL 遍历顶点?

c++ - 错误 : No matching constructor for initialization of 'Matrix_ref<...>'

c++ - 隐式转换中的隐式参数

c++ - 为什么用户定义的移动构造函数会禁用隐式复制构造函数?

c++ - 如何有效地使用 std::async 对指针数组执行操作

c++ - 在 map 中使用 lambda 作为比较器时的匿名类型警告

c++ - c++中的异常机制问题

C++ 类重载运算符

c++ - 如何在 C++ 类中使用列表