Chops Net IP
Loading...
Searching...
No Matches
worker.hpp
Go to the documentation of this file.
1
19#ifndef WORKER_HPP_INCLUDED
20#define WORKER_HPP_INCLUDED
21
22#include <thread>
23
24#include <exception>
25#include <iostream>
26
27#include "asio/io_context.hpp"
28#include "asio/any_io_executor.hpp"
29#include "asio/executor_work_guard.hpp"
30
31namespace chops {
32namespace net {
33
41class worker {
42private:
43 asio::io_context m_ioc;
44 asio::executor_work_guard<asio::io_context::executor_type> m_wg;
45 std::thread m_run_thr;
46
47public:
48 worker() : m_ioc(), m_wg(asio::make_work_guard(m_ioc)), m_run_thr() { }
49
55 asio::io_context& get_io_context() { return m_ioc; }
56
61 void start() {
62 m_run_thr = std::thread([this] () {
63 try {
64 m_ioc.run();
65 }
66 catch (const std::exception& e) {
67 std::cerr << "std::exception caught in worker::start: " << e.what() << std::endl;
68 }
69 catch (...) {
70 std::cerr << "Unknown exception caught in worker::start" << std::endl;
71 }
72 }
73 );
74 }
75
79 void stop() {
80 m_ioc.stop();
81 m_run_thr.join();
82 }
83
88 void reset() {
89 m_wg.reset();
90 m_run_thr.join();
91 }
92
93};
94
95
96} // end net namespace
97} // end chops namespace
98
99#endif
100
Convenience class that combines an executor work guard and a thread, invoking asynchronous operations...
Definition worker.hpp:41
void stop()
Shutdown the executor and join the thread, abandoning any outstanding operations or handlers.
Definition worker.hpp:79
void start()
Start the thread that invokes the underlying asynchronous operations.
Definition worker.hpp:61
asio::io_context & get_io_context()
Provide access to the io_context.
Definition worker.hpp:55
void reset()
Reset the internal work guard and join the thread, waiting for outstanding operations or handlers to ...
Definition worker.hpp:88