Files
libspinscale/include/spinscale/cps/asynchronousBridge.h
T

59 lines
1.5 KiB
C++
Raw Normal View History

2025-12-28 03:54:22 -04:00
#ifndef ASYNCHRONOUS_BRIDGE_H
#define ASYNCHRONOUS_BRIDGE_H
#include <atomic>
2026-05-30 11:57:57 -04:00
#include <boost/asio/io_context.hpp>
#include <boost/asio/post.hpp>
2025-12-28 03:54:22 -04:00
2026-05-17 17:26:21 -04:00
namespace sscl::cps {
2025-12-28 03:54:22 -04:00
class AsynchronousBridge
{
public:
2026-05-30 11:57:57 -04:00
AsynchronousBridge(boost::asio::io_context &io_context)
: isAsyncOperationComplete(false), io_context(io_context)
2025-12-28 03:54:22 -04:00
{}
void setAsyncOperationComplete(void)
{
/** EXPLANATION:
* This empty post()ed message is necessary to ensure that the thread
2026-05-30 11:57:57 -04:00
* that's waiting on the io_context is signaled to wake up and check
* the io_context's queue.
2025-12-28 03:54:22 -04:00
*/
isAsyncOperationComplete.store(true);
2026-05-30 11:57:57 -04:00
boost::asio::post(io_context, []{});
2025-12-28 03:54:22 -04:00
}
2026-05-30 11:57:57 -04:00
void waitForAsyncOperationCompleteOrIoContextStopped(void)
2025-12-28 03:54:22 -04:00
{
for (;;)
{
2026-05-30 11:57:57 -04:00
io_context.run_one();
if (isAsyncOperationComplete.load() || io_context.stopped())
2025-12-28 03:54:22 -04:00
{ break; }
/** EXPLANATION:
2026-02-18 01:13:02 -04:00
* In the puppeteer and mind thread loops we call checkException()
* after run() returns, but we don't have to do that here because
* setException() calls stop().
2025-12-28 03:54:22 -04:00
*
* So if an exception is set on our thread, we'll break out of this
* loop due to the check for stopped() above, and that'll take us
* back out to the main loop, where we'll catch the exception.
*/
}
}
2026-05-30 11:57:57 -04:00
bool exitedBecauseIoContextStopped(void) const
{ return io_context.stopped(); }
2025-12-28 03:54:22 -04:00
private:
std::atomic<bool> isAsyncOperationComplete;
2026-05-30 11:57:57 -04:00
boost::asio::io_context &io_context;
2025-12-28 03:54:22 -04:00
};
2026-05-17 17:26:21 -04:00
} // namespace sscl::cps
2025-12-28 03:54:22 -04:00
#endif // ASYNCHRONOUS_BRIDGE_H