2017-08-30 31 views
3

我写了这个示例代码来测试boost::future继续在我的应用程序中使用。boost :: future :: then()不会返回将来的销毁块

#include <iostream> 
#include <functional> 
#include <unistd.h> 
#include <exception> 

#define BOOST_THREAD_PROVIDES_FUTURE 
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION 

#include <boost/thread/future.hpp> 

void magicNumber(std::shared_ptr<boost::promise<long>> p) 
{ 
    sleep(5); 
    p->set_value(0xcafebabe); 
} 

boost::future<long> foo() 
{ 
    std::shared_ptr<boost::promise<long>> p = 
    std::make_shared<boost::promise<long>>(); 

    boost::future<long> f = p->get_future(); 

    boost::thread t([p](){magicNumber(p);}); 

    t.detach(); 

    return f; 
} 

void bar() 
{ 
    auto f = foo(); 
    f.then([](boost::future<long> f) { std::cout << f.get() << std::endl; }); 
    std::cout << "Should have blocked?" << std::endl; 
} 

int main() 
{ 
    bar(); 

    sleep (6); 

    return 0; 
} 

当编译,连接,并与升压版本1.64.0_1运行,我得到以下输出:

Should have blocked? 
3405691582 

但根据boost::future::then的文档here。 执行应在f.then()在功能bar()被阻止,因为boost::future<void>类型的临时变量应在破坏块,输出应该是

3405691582 
Should have blocked? 

在我的应用程序虽然,调用f.then()是阻断执行,直到继续没有被调用。 这里发生了什么?

+0

我很好奇 - 是必须提升使用率吗?我只能使用标准功能https://gist.github来做同样的事情。com/artemyv/baab7c8c74bb7fde07ebdcf2aee19881 –

+0

@ArtemyVysotsky不,实现相同的功能在这里是没有问题的。这个问题几乎没有好奇心。另外,使用.then在组合性方面似乎更好,而不是使用if-else。你会意识到在std :: async创建期货时会发生同样的行为,它们会阻止破坏,这应该发生在这里,并且也发生在我的应用程序代码中。我的问题是为什么它不会发生在这种情况下。或者也可以被其他人重现。谢谢你的意见。 – vvineett

回答

0

请注意,在使用std::async启动策略为launch::async的过程中,在将来会永远禁止使用析构函数的唯一时间就是文档。

Why is the destructor of a future returned from `std::async` blocking?

答案列出了已经发生围绕这个主题的许多讨论。该提案N3776使它成为C++ 14:

本文提供提议的措词来实现正SG1民意测验澄清~future~shared_future不除了可能在异步的存在阻止。

cppreference.com文件std::async

enter image description here

你的代码永远不会使用异步,所以这将是令人吃惊,如果任何未来衍生毁灭块。

更多生成 同盟很显然,共识是阻止破坏是一个不幸的设计瑕疵,而不是你期望在新扩展中引入的东西(如.then延续)。

我只能假设这是文档的错误的情况下措辞

  • 返回期货表现为从boost ::异步返回的,未来对象的析构函数从此将返回块。这可能会在未来版本中发生变化。

应该被删除。