![](/img/trans.png)
[英](How) Can I get a callback on a boost::asio::io_service when a std::future is ready?
[英]How can I get a future from boost::asio::post?
我正在使用 Boost 1.66.0,其中 asio 內置支持與期貨互操作(現在已經有一段時間了)。 我在網上看到的例子表明了如何在使用async_read
、 async_read_some
等網絡函數時干凈地實現這一點。這是通過提供boost::asio::use_future
代替完成處理程序來完成的,這會導致啟動函數按預期返回future
。
為了從boost::asio::post
獲得相同的行為,我需要提供或包裝我的函數什么樣的對象?
我發布工作的目的是在一個鏈的上下文中執行它,否則等待工作完成,這樣我就可以獲得我想要做的行為:
std::packaged_task<void()> task( [] { std::cout << "Hello world\n"; } );
auto f = task.get_future();
boost::asio::post(
boost::asio::bind_executor(
strand_, std::move( task ) ) );
f.wait();
但是根據boost::asio
文檔, boost::asio::post
的返回類型的推導方式與boost::asio::async_read
等函數的推導方式相同,所以我覺得必須有更好的方法可以避免中間的packaged_task
。 不像async_read
沒有“其他工作”被完成post
那么只提供boost::asio::use_future
不會是有道理的,但我們可以定義一個async_result
性狀得到職位相同的行為。
是否有包裝器或具有定義必要特征的東西以獲得我想要的行為,還是我需要自己定義它?
為了從
boost::asio::post
獲得相同的行為,我需要提供或包裝什么類型的對象?
你不能。 post
是一個無效的操作。 因此,通過post
實現它的唯一選擇是使用打包任務,真的。
它隱藏在“如何獲得相同的行為”部分中(只是不是來自post
):
template <typename Token>
auto async_meaning_of_life(bool success, Token&& token)
{
using result_type = typename asio::async_result<std::decay_t<Token>, void(error_code, int)>;
typename result_type::completion_handler_type handler(std::forward<Token>(token));
result_type result(handler);
if (success)
handler(error_code{}, 42);
else
handler(asio::error::operation_aborted, 0);
return result.get ();
}
您可以將它與未來一起使用:
std::future<int> f = async_meaning_of_life(true, asio::use_future);
std::cout << f.get() << "\n";
或者你可以只使用一個處理程序:
async_meaning_of_life(true, [](error_code ec, int i) {
std::cout << i << " (" << ec.message() << ")\n";
});
簡單演示: Live On Coliru
相同的機制擴展到支持協程(有或沒有例外)。 有一個稍微不同的舞蹈async_result
為短耳預升壓1.66.0。
在這里一起查看所有不同的形式:
#define BOOST_COROUTINES_NO_DEPRECATION_WARNING
#include <iostream>
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/use_future.hpp>
using boost::system::error_code;
namespace asio = boost::asio;
template <typename Token>
auto async_meaning_of_life(bool success, Token&& token)
{
#if BOOST_VERSION >= 106600
using result_type = typename asio::async_result<std::decay_t<Token>, void(error_code, int)>;
typename result_type::completion_handler_type handler(std::forward<Token>(token));
result_type result(handler);
#else
typename asio::handler_type<Token, void(error_code, int)>::type
handler(std::forward<Token>(token));
asio::async_result<decltype (handler)> result (handler);
#endif
if (success)
handler(error_code{}, 42);
else
handler(asio::error::operation_aborted, 0);
return result.get ();
}
void using_yield_ec(asio::yield_context yield) {
for (bool success : { true, false }) {
boost::system::error_code ec;
auto answer = async_meaning_of_life(success, yield[ec]);
std::cout << __FUNCTION__ << ": Result: " << ec.message() << "\n";
std::cout << __FUNCTION__ << ": Answer: " << answer << "\n";
}
}
void using_yield_catch(asio::yield_context yield) {
for (bool success : { true, false })
try {
auto answer = async_meaning_of_life(success, yield);
std::cout << __FUNCTION__ << ": Answer: " << answer << "\n";
} catch(boost::system::system_error const& e) {
std::cout << __FUNCTION__ << ": Caught: " << e.code().message() << "\n";
}
}
void using_future() {
for (bool success : { true, false })
try {
auto answer = async_meaning_of_life(success, asio::use_future);
std::cout << __FUNCTION__ << ": Answer: " << answer.get() << "\n";
} catch(boost::system::system_error const& e) {
std::cout << __FUNCTION__ << ": Caught: " << e.code().message() << "\n";
}
}
void using_handler() {
for (bool success : { true, false })
async_meaning_of_life(success, [](error_code ec, int answer) {
std::cout << "using_handler: Result: " << ec.message() << "\n";
std::cout << "using_handler: Answer: " << answer << "\n";
});
}
int main() {
asio::io_service svc;
spawn(svc, using_yield_ec);
spawn(svc, using_yield_catch);
std::thread work([] {
using_future();
using_handler();
});
svc.run();
work.join();
}
版畫
using_yield_ec: Result: Success
using_yield_ec: Answer: 42
using_yield_ec: Result: Operation canceled
using_yield_ec: Answer: 0
using_yield_catch: Answer: 42
using_future: Answer: 42
using_yield_catch: Caught: Operation canceled
using_future: Answer: using_future: Caught: Operation canceled
using_handler: Result: Success
using_handler: Answer: 42
using_handler: Result: Operation canceled
using_handler: Answer: 0
這就是我想出的,它基本上包裝了asio::post
並插入了一個承諾/未來對。 我認為它也可以適應您的需求。
// outer scope setup
asio::io_context context;
asio::io_context::strand strand(context);
std::future<void> async_send(tcp::socket& socket, std::string message) {
auto buffered = std::make_shared<std::string>(message);
std::promise<void> promise;
auto future = promise.get_future();
// completion handler which only sets the promise.
auto handler = [buffered, promise{std::move(promise)}](asio::error_code, std::size_t) mutable {
promise.set_value();
};
// post async_write call to strand. Thas *should* protecte agains concurrent
// writes to the same socket from multiple threads
asio::post(strand, [buffered, &socket, handler{std::move(handler)}]() mutable {
asio::async_write(socket, asio::buffer(*buffered), asio::bind_executor(strand, std::move(handler)));
});
return future;
}
可以在未來不失效的情況下移動承諾。
適應您的情況,它可能是這樣的:
template<typename C>
std::future<void> post_with_future(C&& handler)
{
std::promise<void> promise;
auto future = promise.get_future();
auto wrapper = [promise{std::move(promise)}]{ // maybe mutable required?
handler();
promise.set_value();
};
// need to move in, cause the promise needs to be transferred. (i think)
asio::post(strand, std::move(wrapper));
return future;
}
我會很高興對這些線路的一些反饋,因為我自己只是在學習整個事情:)
希望能幫到你,馬蒂
@ MartiNitro的有想法packaged_task
已成為庫的一部分:現在你可以發布packaged_task
,它會奇跡般地恢復它的未來:
auto f = post(strand_, std::packaged_task<int()>(task));
#include <boost/asio.hpp>
#include <iostream>
#include <future>
using namespace std::chrono_literals;
int task() {
std::this_thread::sleep_for(1s);
std::cout << "Hello world\n";
return 42;
}
int main() {
boost::asio::thread_pool ioc;
auto strand_ = make_strand(ioc.get_executor());
auto f = post(strand_, std::packaged_task<int()>(task));
// optionally wait for future:
f.wait();
// otherwise .get() would block:
std::cout << "Answer: " << f.get() << "\n";
ioc.join();
}
印刷
Hello world
Answer: 42
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.