Line data Source code
1 : #ifndef THINGER_ASIO_WORKER_CLIENT_HPP
2 : #define THINGER_ASIO_WORKER_CLIENT_HPP
3 :
4 : #include <string>
5 : #include <mutex>
6 : #include <condition_variable>
7 : #include <atomic>
8 :
9 : namespace thinger::asio {
10 :
11 : /**
12 : * Base class for clients that use ASIO workers.
13 : * This allows automatic management of worker threads based on active clients.
14 : * Provides common implementation for wait() and state management.
15 : */
16 : class worker_client {
17 : protected:
18 : mutable std::mutex wait_mutex_;
19 : mutable std::condition_variable wait_cv_;
20 : std::atomic<bool> running_{false};
21 : std::string service_name_;
22 :
23 : public:
24 : explicit worker_client(const std::string& service_name);
25 : virtual ~worker_client();
26 :
27 : /**
28 : * Start the client service
29 : * Default implementation sets running_ to true
30 : * Derived classes should call this base implementation
31 : * @return true if started successfully
32 : */
33 295 : virtual bool start() {
34 295 : running_ = true;
35 295 : return true;
36 : }
37 :
38 : /**
39 : * Stop the client service
40 : * Default implementation sets running_ to false and notifies waiters
41 : * Derived classes should call this base implementation
42 : * @return true if stopped successfully
43 : */
44 599 : virtual bool stop() {
45 599 : running_ = false;
46 599 : notify_stopped();
47 599 : return true;
48 : }
49 :
50 : /**
51 : * Check if the client service is running
52 : * @return true if running
53 : */
54 310 : virtual bool is_running() const { return running_; }
55 :
56 : /**
57 : * Wait until the service stops
58 : * Blocks the calling thread until stop() is called
59 : */
60 0 : virtual void wait() {
61 0 : std::unique_lock<std::mutex> lock(wait_mutex_);
62 0 : if (running_) {
63 0 : wait_cv_.wait(lock, [this] { return !running_.load(); });
64 : }
65 0 : }
66 :
67 : /**
68 : * Get a descriptive name for this client (for debugging/logging)
69 : * @return service name
70 : */
71 596 : const std::string& get_service_name() const { return service_name_; }
72 :
73 : protected:
74 : /**
75 : * Notify that the service has stopped
76 : * Should be called by derived classes in their stop() implementation
77 : */
78 599 : void notify_stopped() {
79 599 : wait_cv_.notify_all();
80 599 : }
81 : };
82 :
83 : } // namespace thinger::asio
84 :
85 : #endif // THINGER_ASIO_WORKER_CLIENT_HPP
|