Boost :: ASIO: Как я могу получить возвращаемое значение из io_service?

Как я могу получить возвращаемые значения из 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;
}

Но я все еще хочу, чтобы с привязкой было что-то попроще или что-то в этом роде.

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

Другие решения

Вот как вы можете сделать это, используя asio::use_future а также async_result, Обратите внимание, что я сохранил пример простым, передавая вещи по значению и используя жестко закодированные аргументы для суммы.

#include <iostream>
#include <thread>
#include <asio.hpp>
#include <asio/use_future.hpp>

int get_sum(int a, int b)
{
return a + b;
}

template <typename Func, typename CompletionFunction>
auto perform_asyncly(asio::io_service& ios, Func f, CompletionFunction cfun)
{

using handler_type = typename asio::handler_type
<CompletionFunction, void(asio::error_code, int)>::type;

handler_type handler{cfun};
asio::async_result<handler_type> result(handler);

ios.post([handler, f]() mutable {
handler(asio::error_code{}, f(2, 2));
});

return result.get();
}

int main() {
asio::io_service ios;
asio::io_service::work wrk{ios};
std::thread t{[&]{ ios.run(); }};
auto res = perform_asyncly(ios, get_sum, asio::use_future);
std::cout << res.get() << std::endl;

t.join();

return 0;
}
1

Если цель состоит в том, чтобы иметь простую функцию, похожую на привязку строки, которая также собирает для вас возвращаемое значение, вы можете реализовать ее следующим образом:

#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;
}
0

Приведенное ниже решение — это то, что я планирую использовать в своем собственном приложении. Три особенности:

  1. Функции / лямбды являются аргументами для 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 (огромное спасибо это решение):

#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
0