From d3a10d7190637029c110b1a6209fbe8783cbdd64 Mon Sep 17 00:00:00 2001 From: Vincent Batts Date: Sat, 8 Feb 2025 19:56:52 -0500 Subject: [PATCH] *: adding a threaded worker example Signed-off-by: Vincent Batts --- account.h | 3 +++ main.cpp | 4 ++++ meson.build | 6 +++++- worker.cpp | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 worker.cpp diff --git a/account.h b/account.h index 011960a..5631f7c 100644 --- a/account.h +++ b/account.h @@ -1,4 +1,6 @@ +#ifndef ACCOUNT_H +#define ACCOUNT_H /* * ===================================================================================== * Class: Account @@ -39,3 +41,4 @@ class Account }; /* ----- end of class Account ----- */ +#endif diff --git a/main.cpp b/main.cpp index 73caee6..204e693 100644 --- a/main.cpp +++ b/main.cpp @@ -25,5 +25,9 @@ using namespace std; int main(int argc, char* argv[]) { Account account(0.0); + account.deposit(100.5); // Add some money + account.deposit(50.25); // Add more money + std::cout << "Current Balance: " << account.getBalance() << std::endl; + return EXIT_SUCCESS; } diff --git a/meson.build b/meson.build index 27c1cb6..aa78d8f 100644 --- a/meson.build +++ b/meson.build @@ -8,5 +8,9 @@ a = run_command('date', check: true) read_exe = executable('read', 'read.c', link_language : 'c',) readpp_exe = executable('read++', 'read++.cpp') +worker_exe = executable('worker', 'worker.cpp') + account_sources = ['main.cpp', 'account.cpp', 'account.h'] -account_exe = executable('account', account_sources) +account_exe = executable('account', account_sources, + cpp_args: ['-std=c++23'], + ) diff --git a/worker.cpp b/worker.cpp new file mode 100644 index 0000000..19ecbb9 --- /dev/null +++ b/worker.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include + +// https://en.cppreference.com/w/cpp/thread/thread +// 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; + +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 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; +}