Boost :: ASIO:如何从io_service中捕获返回值?

时间:2017-03-20 08:55:12

标签: c++ boost boost-asio stdbind asio

如何从boost::asio::io_service捕获返回值?是否可以使用一些绑定或任何简单的构造,不涉及重写函数?

以下是一个最小的例子。我正在尝试捕获GetSum()的价值回报:

#include <iostream>
#include <boost/asio.hpp>
#include <functional>

using namespace std;

void SayHello()
{
    std::cout<<"Hello!"<<std::endl;
}

template <typename T>
T GetSum(T a, T b)
{
    std::cout<<"Adding " << a << " and " << b << std::endl;
    return a+b;
}

int main(int argc, char *argv[])
{
    boost::asio::io_service ioservice;

    ioservice.post(&SayHello);
    ioservice.post(std::bind(&GetSum<double>,1,2));

    ioservice.run();
    return 0;
}

为什么呢?因为我正在设计一个线程池,并且我正在考虑我的选择,使用户可以获得其函数的返回值,而无需手动将其函数与其他函数包装,从而捕获他的返回值

我的解决方案:

int main(int argc, char *argv[])
{
    boost::asio::io_service ioservice;

    ioservice.post(&SayHello);
    double sum;
    ioservice.post([&sum]()
    {
        sum = GetSum(1,2);
    });

    ioservice.run();
    std::cout<< sum <<std::endl; //is 3
    return 0;
}

但是我仍然希望有一个更简单的绑定或其他东西。

4 个答案:

答案 0 :(得分:2)

我想出了一个灵感来自使用类似std::future之类的建议的解决方案。所以我使用std::future,代码可以运行。

我所做的只是继承自io_service,并创建一个具有返回值未来的新方法post_with_future。我很感激批评这个解决方案来改进它。

#include <iostream>
#include <functional>
#include <type_traits>
#include <future>
#include <boost/asio.hpp>

class future_io_service : public boost::asio::io_service
{
public:
    template <typename FuncType>
    std::future<typename std::result_of<FuncType()>::type> post_with_future(FuncType&& func)
    {
        //keep in mind that std::result_of is std::invoke_result in C++17
        typedef typename std::result_of<FuncType()>::type return_type;
        typedef typename std::packaged_task<return_type()> task_type;
        //since post requires that the functions in it are copy-constructible, we use a shared pointer for the packaged_task since it's only movable and non-copyable
        std::shared_ptr<task_type> task = std::make_shared<task_type>(std::move(func));
        std::future<return_type> returned_future = task->get_future();
        this->post(std::bind(&task_type::operator(),task));
        return returned_future;
    }
};

void SayHello()
{
    std::cout<<"Hello!"<<std::endl;
}

template <typename T>
T GetSum(T a, T b)
{
    std::cout<<"Adding " << a << " and " << b << std::endl;
    return a+b;
}

int main()
{
    future_io_service ioservice;

    ioservice.post(&SayHello);
    auto sum = ioservice.post_with_future(std::bind(&GetSum<int>,1,2));
    ioservice.run();
    std::cout<<sum.get()<<std::endl; //result is 3
    return 0;
}

答案 1 :(得分:1)

这是通过使用Rick has 241 cars John won 505 dollars asio::use_future来实现的。请注意,我通过按值传递事物并使用硬编码参数来保持示例简单。

async_result

答案 2 :(得分:0)

如果目标是使用一个简单的单线程绑定函数来捕获返回值,则可以像下面这样实现:

#include <iostream>
#include <boost/asio.hpp>
#include <functional>

using namespace std;

void SayHello()
{
  std::cout<<"Hello!"<<std::endl;
}

template <typename T>
T GetSum(T a, T b)
{
  std::cout<<"Adding " << a << " and " << b << std::endl;
  return a+b;
}

template<typename R, typename F, typename... Args>
auto bind_return_value(R& r, F&& f, Args&&... args)
{
  return [&]()
    {
      r = f(std::forward<Args>(args)...);
    };
}

int main(int argc, char *argv[])
{
  boost::asio::io_service ioservice;

  ioservice.post(&SayHello);
  double sum;
  ioservice.post(bind_return_value(sum, &GetSum<double>, 1, 2));

  ioservice.run();
  std::cout<< sum <<std::endl; //is 3
  return 0;
}

答案 3 :(得分:0)

以下解决方案是我计划在自己的应用程序中使用的解决方案。三个功能:

  1. 函数/ lambdas是post_function_use_future()的参数。要求:函数必须返回非void的值,并且它们的输入参数必须为零。请注意,SayHello()现在返回一个int。

  2. 可以使用任何Asio上下文,例如io_context和strands。

  3. 在撰写本文时,没有过时的功能。

在主cpp文件中:

#include <iostream>
#include <thread>
#include <boost/asio.hpp>
#include "function_return_type.hpp"

template <typename ExecutionContext, typename FuncWithReturnNoArgs>
auto post_function_use_future(ExecutionContext& ctx, FuncWithReturnNoArgs f)
{
    using handler_type = typename boost::asio::handler_type
        <boost::asio::use_future_t<>, void(boost::system::error_code, return_type_t<FuncWithReturnNoArgs>)>::type;

    using Sig = void(boost::system::error_code, return_type_t<FuncWithReturnNoArgs>);
    using Result = typename boost::asio::async_result<boost::asio::use_future_t<>, Sig>;
    using Handler = typename Result::completion_handler_type;

    Handler handler(std::forward<decltype(boost::asio::use_future)>(boost::asio::use_future));
    Result result(handler);

    boost::asio::post(ctx, [handler, f]() mutable {
        handler(boost::system::error_code(), f());
    });

    return result.get();
}

namespace asio = boost::asio;

int SayHello()
{
    std::cout << "Hello!" << std::endl;
    return 0;
}

template <typename T>
T GetSum(T a, T b)
{
    std::cout << "Adding " << a << " and " << b << std::endl;
    return a + b;
}

int main() {
    asio::io_context io;
    auto wg = asio::make_work_guard(io);

    std::thread t{ [&] { io.run(); } };

    auto res1 = post_function_use_future(io, SayHello);
    res1.get(); // block until return value received.

    auto res2 = post_function_use_future(io, []() {return  GetSum(20, 14); });
    std::cout << res2.get() << std::endl; // block until return value received.

    wg.reset();
    if(t.joinable()) t.join();

    return 0;
}

在function_return_type.hpp文件中(对this solution表示巨大的敬意):

#ifndef FUNCTION_RETURN_TYPE_HPP
#define FUNCTION_RETURN_TYPE_HPP

template <typename F>
struct return_type_impl;

template <typename R, typename... Args>
struct return_type_impl<R(Args...)> { using type = R; };

template <typename R, typename... Args>
struct return_type_impl<R(Args..., ...)> { using type = R; };

template <typename R, typename... Args>
struct return_type_impl<R(*)(Args...)> { using type = R; };

template <typename R, typename... Args>
struct return_type_impl<R(*)(Args..., ...)> { using type = R; };

template <typename R, typename... Args>
struct return_type_impl<R(&)(Args...)> { using type = R; };

template <typename R, typename... Args>
struct return_type_impl<R(&)(Args..., ...)> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args...)> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args..., ...)> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args...) &> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args..., ...) &> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args...) && > { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args..., ...) && > { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args...) const> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args..., ...) const> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args...) const&> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args..., ...) const&> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args...) const&&> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args..., ...) const&&> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args...) volatile> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args..., ...) volatile> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args...) volatile&> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args..., ...) volatile&> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args...) volatile&&> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args..., ...) volatile&&> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args...) const volatile> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args..., ...) const volatile> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args...) const volatile&> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args..., ...) const volatile&> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args...) const volatile&&> { using type = R; };

template <typename R, typename C, typename... Args>
struct return_type_impl<R(C::*)(Args..., ...) const volatile&&> { using type = R; };

template <typename T, typename = void>
struct return_type
    : return_type_impl<T> {};

template <typename T>
struct return_type<T, decltype(void(&T::operator()))>
    : return_type_impl<decltype(&T::operator())> {};

template <typename T>
using return_type_t = typename return_type<T>::type;

#endif