我需要使用 boost asio 库实现自定义异步操作。该操作本身将由第三方库执行。
我遵循的方法是:
boost::asio::async_initiate
启动异步操作。为此,我正在实现启动功能boost::asio::async_initiate
传递给启动函数复制代码如下。这里的第 3 方库是用单独的线程和布尔标志来模拟的:
#include <iostream>
#include <string>
#include <thread>
#include <functional>
#include <atomic>
#include <boost/asio.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/experimental/awaitable_operators.hpp>
#include <boost/asio/experimental/co_spawn.hpp>
std::atomic<bool> asyncOpStarted = false;
using signature = void(std::string);
std::function<signature> completionHandler;
// Dummy implementation to simulate the async operation
void start_operation()
{
asyncOpStarted = true;
std::cout << "Async operation starting..." << std::endl;
}
void do_async_loop()
{
while (!asyncOpStarted) {
// sleep & check if operation started
std::cout << "Waiting for async start..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
};
std::cout << "Async operation started..." << std::endl;
// simualate delay
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Async operation finished. Invoke completion handler..." << std::endl;
completionHandler("Done");
}
// Async operation implementation
template <typename CompletionToken>
auto async_do_operation(boost::asio::io_context& io, CompletionToken&& token)
{
return boost::asio::async_initiate<CompletionToken, signature>(
[&](auto&& handler) {
// I need to store "handler" here
// This doesn't work. std::function<...> requires handler to be copyable:
//completionHandler = [h = std::move(handler)](std::string res) mutable {
// h(res);
//};
start_operation();
},
std::move(token)
);
}
int main()
{
std::thread t(do_async_loop);
boost::asio::io_context io;
boost::asio::co_spawn(io, [&]() -> boost::asio::awaitable<void> {
try {
// Use `boost::asio::use_awaitable` as the completion token
auto result = co_await async_do_operation(io, boost::asio::use_awaitable);
std::cout << "Coroutine: " << result << std::endl;
} catch (...) {
std::cerr << "Exception caught" << std::endl;
}
}, boost::asio::detached);
// Run the io_context to process async events
io.run();
}
我在步骤(2)中失败了。无法以任何方式存储完成处理程序。 我尝试了以下方法:
std::function
并将完成处理程序移动到捕获列表中std::function
要求处理程序可复制所以,我的问题是:
提前致谢。
您可以使用相对较新的
asio::any_completion_handler
类型擦除容器。
这是一个简化版本,还修复了一些问题:
std::forward
而不是std::move
std::move
(在 async_initiate
中)#include <boost/asio.hpp>
#include <iostream>
#include <string>
#include <thread>
namespace asio = boost::asio;
std::atomic<bool> asyncOpStarted = false;
using signature = void(std::string);
asio::any_completion_handler<signature> completionHandler;
// Dummy implementation to simulate the async operation
void start_operation() {
asyncOpStarted = true;
std::cout << "Async operation starting..." << std::endl;
}
void do_async_loop() {
while (!asyncOpStarted) {
// sleep & check if operation started
std::cout << "Waiting for async start..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
};
std::cout << "Async operation started..." << std::endl;
// simualate delay
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Async operation finished. Invoke completion handler..." << std::endl;
completionHandler("Done");
}
template <typename Token> //
auto async_do_operation(asio::any_io_executor ex, Token&& token) {
return asio::async_initiate<Token, signature>(
[&](auto&& handler) {
completionHandler = //
[w = make_work_guard(ex), handler = std::move(handler)] //
(std::string res) mutable //
{ //
std::move(handler)(std::move(res));
};
start_operation();
},
std::forward<Token>(token));
}
asio::awaitable<void> coro() try {
auto ex = co_await asio::this_coro::executor;
std::cout << "Coroutine: " << co_await async_do_operation(ex, asio::deferred) << std::endl;
} catch (...) {
std::cerr << "Exception caught" << std::endl;
}
int main() {
std::thread t(do_async_loop);
asio::io_context io;
co_spawn(io, coro, asio::detached);
io.run();
t.join();
}
输出:
Waiting for async start...
Async operation starting...
Async operation started...
Async operation finished. Invoke completion handler...
Coroutine: Done