From 06b00b9f971be3111cac9fbfa2d0a035a95ba1dc Mon Sep 17 00:00:00 2001 From: Vincent Batts Date: Mon, 10 Feb 2025 13:59:21 -0500 Subject: [PATCH] worker: put this threaded worker into a class for cleanliness Signed-off-by: Vincent Batts --- worker.cpp | 55 ++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 37 insertions(+), 18 deletions(-) diff --git a/worker.cpp b/worker.cpp index 19ecbb9..0e46134 100644 --- a/worker.cpp +++ b/worker.cpp @@ -7,26 +7,45 @@ // https://en.cppreference.com/w/cpp/thread/mutex // https://en.cppreference.com/w/cpp/thread/condition_variable -std::mutex mtx; -std::condition_variable cv; -bool ready = false; +namespace Dang { + class Worker { + public: + Worker() { + this->ready = false; + //init(); + }; + + void run() { + std::unique_lock lock(this->mtx); + this->cv.wait(lock, [this] { return this->ready; }); // Wait until 'ready' is set to true + std::cout << "Daemon process woke up!" << std::endl; + }; -void worker() { - std::unique_lock lock(mtx); - cv.wait(lock, [] { return ready; }); // Wait until 'ready' is set to true - std::cout << "Daemon process woke up!" << std::endl; + int work() { + std::thread daemon([this] {this->run();}); + + std::this_thread::sleep_for(std::chrono::seconds(5)); + { + std::lock_guard lock(this->mtx); + this->ready = true; + } + this->cv.notify_one(); + + daemon.join(); + return 0; + }; + + private: + std::mutex mtx; + std::condition_variable cv; + bool ready; + }; } + int main() { - std::thread daemon(worker); - - std::this_thread::sleep_for(std::chrono::seconds(5)); - { - std::lock_guard lock(mtx); - ready = true; - } - cv.notify_one(); - - daemon.join(); - return 0; + Dang::Worker worker; + return worker.work(); } + +// vim:set sts=2 sw=2 et: