8 IoContextWithThread
IoContextWithThread provides a boost asio
io_context and a
std::thread which calls run() on the io_context.
An executor_work_guard
instance is used to ensure run() on the io_context
doesn't exit prematurely.
IoContextWithThread.h
// IoContextWithThread.h
//
// Author David Barrett-Lennard
// (C)opyright Cedanet Pty Ltd 2021
#pragma once
#ifndef Ceda_cxThread_IoContextWithThread_H
#define Ceda_cxThread_IoContextWithThread_H
#include <boost/asio.hpp>
#include <thread>
namespace ceda
{
struct IoContextWithThread
{
IoContextWithThread() :
workGuard(io_context.get_executor())
{
thread = std::thread(
[&]()
{
io_context.run();
});
}
~IoContextWithThread()
{
workGuard.reset();
thread.join();
}
boost::asio::io_context io_context;
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> workGuard;
std::thread thread;
};
} // namespace ceda
#endif // include guard