为什么我的带有 boost::future 的 .then 的链式方法没有被调用?

Why my chained methods with boost::future's .then are not invoked?

本文关键字:方法 调用 我的 boost future 为什么 then      更新时间:2023-10-16

我有以下一段代码:

#define BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
#include <iostream>
#include <thread>
#include <boost/thread/future.hpp>
using namespace boost;
int foo(boost::future<int> x) {
  std::cout << "first stage(" << x.get() << ")" << 'n';
  return x.get();
}
int main()
{
  std::cout << "making promise" << 'n';
  boost::promise<int> p;
  boost::future<int> f = p.get_future();
  std::cout << "future chain made" << 'n';
  std::thread t([&](){
    f.then(foo)
      .then([](boost::future<int> x){ std::cout << "second stage " << 2 * x.get() << 'n'; return 2 * x.get(); })
      .then([](boost::future<int> x){ std::cout << "final stage " << 10 * x.get() << 'n'; });
  });
  std::cout << "fulfilling promise" << 'n';
  p.set_value(42);
  std::cout << "promise fulfilled" << 'n';
  t.join();
}

我这样编译它:

g++ -g -Wall -std=c++14 -DBOOST_THREAD_VERSION=4 main.cpp -lboost_thread -lboost_system -pthread

我得到以下输出:

making promise
future chain made
fulfilling promise
promise fulfilled
first stage(42)

为什么我的 2 个 lambda 链接在线程中t没有被调用?我错过了什么吗?

我尝试添加boost::future::get()调用,但随后出现异常:

  std::cout << "fulfilling promise" << 'n';
  p.set_value(42);
  std::cout << "promise fulfilled" << 'n';
  std::cout << "value " << f.get() << 'n';
  t.join();

错误:

making promise
future chain made
fulfilling promise
promise fulfilled
first stage(42)
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::future_uninitialized> >'
  what():  Operation not permitted on an object without an associated state.
[1]    20875 abort      ./main

我正在使用提升 1.58.0 和 gcc 5.4.0

在线源链接(带有booost 1.58.0和gcc 5.3.0)http://melpon.org/wandbox/permlink/G8rqt2eHUwI4nzz8

正如一位伟大的诗人曾经写过的那样,"等待它"。

std::thread t([&](){
  f.then(foo)
  .then([](boost::shared_future<int> x){ std::cout << "second stage " << 2 * x.get() << 'n'; return 2 * x.get(); })
  .then([](boost::shared_future<int> x){ std::cout << "final stage " << 10 * x.get() << 'n'; })
  .get();
});

该线程除了设置期货链外什么都不做。 它不运行其中任何一个。

你启动链(

用你的集合),你等待链被设置(有连接),但在链完成之前主退出。 你会很"幸运",在进程退出之前运行一个。

真的,你应该在主线程中设置链,并在线程t中等待链的最后一个未来。 那么你的代码就更有意义了。

auto last = f.then(foo)
  .then([](boost::shared_future<int> x){ std::cout << "second stage " << 2 * x.get() << 'n'; return 2 * x.get(); })
  .then([](boost::shared_future<int> x){ std::cout << "final stage " << 10 * x.get() << 'n'; });
std::thread t([&](){
  last.get();
});

这突出了线程 t 没有用处的事实:将主线程中的 t.join() 替换为 last.get() 并完全删除变量t

正如下面的评论中所述,您还调用了两次get:要使其正常工作,您需要一个shared_future。 这可能就是为什么你的运气始终如一的原因,因为第二个得到可能会阻塞线程。