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 22194 : std::thread::id worker_thread::start() {
9 22194 : if(thread_.joinable()) return thread_.get_id();
10 :
11 22194 : std::promise<std::thread::id> promise;
12 44388 : thread_ = std::thread([this, &promise]{
13 22194 : LOG_DEBUG("worker thread started: {}", worker_name_);
14 :
15 : // start the async work in the child
16 22194 : async_worker();
17 :
18 : // flag starts to true, so the caller can return (thread_ may not be assigned yet)
19 22194 : promise.set_value(std::this_thread::get_id());
20 :
21 : // call async worker
22 22194 : worker_.start();
23 :
24 : // stop
25 22194 : LOG_DEBUG("[{}] worker thread stopped", worker_name_);
26 44388 : });
27 :
28 : // wait for thread to be initialized
29 22194 : auto future = promise.get_future();
30 22194 : future.wait();
31 22194 : return future.get();
32 22194 : }
33 :
34 42650 : bool worker_thread::stop() {
35 42650 : if(!thread_.joinable()) return false;
36 :
37 22194 : LOG_DEBUG("stopping worker thread: {}", worker_name_);
38 22194 : worker_.stop();
39 22194 : thread_.join();
40 22194 : return true;
41 : }
42 :
43 6884 : void worker_thread::shutdown() {
44 6884 : worker_.shutdown();
45 6884 : }
46 :
47 56229 : boost::asio::io_context &worker_thread::get_io_context() {
48 56229 : return worker_.get_io_context();
49 : }
50 :
51 22194 : worker_thread::worker_thread(std::string worker_name) :
52 22194 : worker_name_(std::move(worker_name))
53 : {
54 22194 : }
55 :
56 44388 : worker_thread::~worker_thread(){
57 : //LOG_DEBUG("worker thread deleted: %s", worker_name_.c_str());
58 44388 : }
59 :
60 0 : void worker_thread::set_thread_name(std::string worker_name){
61 0 : worker_name_ = std::move(worker_name);
62 0 : }
63 :
64 0 : void worker_thread::run(std::function<void()> handler) {
65 0 : boost::asio::dispatch(worker_.get_io_context(), std::move(handler));
66 0 : }
67 :
68 : }
|