From 067c928e4767d7560376662e64630b0c0aaed9e1 Mon Sep 17 00:00:00 2001 From: Hayodea Hakol Date: Wed, 10 Sep 2025 11:35:09 -0400 Subject: [PATCH] AsyncBridge: Add new wrapper class that bridges async sequences This class encapsulates all the logic and operations required to correctly bridge an async operation into a sync function. In particular, it also makes it less easy to forget to check if the io_service exited because it was stop()ped. --- include/asynchronousBridge.h | 47 ++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 include/asynchronousBridge.h diff --git a/include/asynchronousBridge.h b/include/asynchronousBridge.h new file mode 100644 index 0000000..96add90 --- /dev/null +++ b/include/asynchronousBridge.h @@ -0,0 +1,47 @@ +#ifndef ASYNCHRONOUS_BRIDGE_H +#define ASYNCHRONOUS_BRIDGE_H + +#include +#include + +namespace smo { + +class AsynchronousBridge +{ +public: + AsynchronousBridge(boost::asio::io_service &io_service) + : io_service(io_service), isAsyncOperationComplete(false) + {} + + void setAsyncOperationComplete(void) + { + /** EXPLANATION: + * This empty post()ed message is necessary to ensure that the thread + * that's waiting on the io_service is signaled to wake up and check + * the io_service's queue. + */ + isAsyncOperationComplete.store(true); + io_service.post([]{}); + } + + void waitForAsyncOperationCompleteOrIoServiceStopped(void) + { + for (;;) + { + io_service.run_one(); + if (isAsyncOperationComplete.load() || io_service.stopped()) + { break; } + } + } + + bool exitedBecauseIoServiceStopped(void) const + { return io_service.stopped(); } + +private: + std::atomic isAsyncOperationComplete; + boost::asio::io_service &io_service; +}; + +} // namespace smo + +#endif // ASYNCHRONOUS_BRIDGE_H