Line data Source code
1 : #include "worker_thread.hpp"
2 : #include "../util/logger.hpp"
3 : #include <future>
4 : #include <boost/asio/dispatch.hpp>
5 :
6 : namespace thinger::asio{
7 :
8 22952 : std::thread::id worker_thread::start() {
9 22952 : if(thread_.joinable()) return thread_.get_id();
10 :
11 22952 : std::promise<std::thread::id> promise;
12 45904 : thread_ = std::thread([this, &promise]{
13 22952 : LOG_DEBUG("worker thread started: {}", worker_name_);
14 :
15 : // start the async work in the child
16 22952 : async_worker();
17 :
18 : // flag starts to true, so the caller can return
19 22952 : promise.set_value(thread_.get_id());
20 :
21 : // call async worker
22 22952 : worker_.start();
23 :
24 : // stop
25 22952 : LOG_DEBUG("[{}] worker thread stopped", worker_name_);
26 45904 : });
27 :
28 : // wait for thread to be initialized
29 22952 : auto future = promise.get_future();
30 22952 : future.wait();
31 22952 : return future.get();
32 22952 : }
33 :
34 22952 : bool worker_thread::stop() {
35 22952 : if(!thread_.joinable()) return false;
36 :
37 22952 : LOG_INFO("stopping worker thread: {}", worker_name_);
38 22952 : worker_.stop();
39 22952 : thread_.join();
40 22952 : return true;
41 : }
42 :
43 908 : boost::asio::io_context &worker_thread::get_io_context() {
44 908 : return worker_.get_io_context();
45 : }
46 :
47 22952 : worker_thread::worker_thread(std::string worker_name) :
48 22952 : worker_name_(std::move(worker_name))
49 : {
50 22952 : }
51 :
52 45904 : worker_thread::~worker_thread(){
53 : //LOG_DEBUG("worker thread deleted: %s", worker_name_.c_str());
54 45904 : }
55 :
56 0 : void worker_thread::set_thread_name(std::string worker_name){
57 0 : worker_name_ = std::move(worker_name);
58 0 : }
59 :
60 0 : void worker_thread::run(std::function<void()> handler) {
61 0 : boost::asio::dispatch(worker_.get_io_context(), std::move(handler));
62 0 : }
63 :
64 : }
|