I have an asynchronous operation by an external library that I can't change, but I can give a callback
to. I want to wait for it to finish but without blocking the io_context
.
Something like:
// Example callback-based operation
void exampleAsyncOperation(std::function<void(boost::system::error_code)> callback) {
std::thread t([=]() {
std::this_thread::sleep_for(std::chrono::seconds(1));
callback(boost::system::error_code());
});
t.detach();
}
boost::asio::awaitable<void> NRClient::callAsyncOperation() {
std::promise<boost::system::error_code> promise;
auto future = promise.get_future();
example_async_operation([&](boost::system::error_code ec) { promise.set_value(ec); });
future.wait(); // this should be something that won't block the thread
}
Or is there something else I can put in the callback to get this functionality?
I ended up copying example from asio's repository https://github.com/chriskohlhoff/asio/blob/fa27820c05afd740fa2adc1ecfb9da5afe026443/asio/src/examples/cpp20/operations/c_callback_wrapper.cpp