From 1c15df6bfc385a46b4e7e2cccf2a7abefa4521d3 Mon Sep 17 00:00:00 2001 From: Joel Bodenmann Date: Mon, 10 Jun 2024 03:08:34 +0200 Subject: [PATCH 1/2] wip --- examples/timer/main.cpp | 4 ++-- lib/timer.hpp | 12 ++++++++---- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/examples/timer/main.cpp b/examples/timer/main.cpp index 4c1ffdd..8b29fda 100644 --- a/examples/timer/main.cpp +++ b/examples/timer/main.cpp @@ -27,7 +27,7 @@ main() print_time(std::cout); std::cout << " | periodic 1: (" << i++ << ") --- thread: " << std::this_thread::get_id() << std::endl; }); - +#if 0 // A timer firing at random intervals jbo::timers::manager::instance().periodic(100ms, 1000ms, []{ print_time(std::cout); @@ -39,7 +39,7 @@ main() print_time(std::cout); std::cout << " | Single Shot!" << std::endl; }); - +#endif std::this_thread::sleep_for(5s); std::cout << "stopping timer executor..." << std::endl; diff --git a/lib/timer.hpp b/lib/timer.hpp index 11c1408..707bd58 100644 --- a/lib/timer.hpp +++ b/lib/timer.hpp @@ -361,7 +361,8 @@ namespace jbo::timers { m_stop.clear(); - m_task_thread = std::thread(&executor::task_worker, this); + m_task_thread_0 = std::thread(&executor::task_worker, this); + m_task_thread_1 = std::thread(&executor::task_worker, this); m_ticker_thread = std::thread(&executor::tick_worker, this); } @@ -374,15 +375,18 @@ namespace jbo::timers if (m_ticker_thread.joinable()) m_ticker_thread.join(); - if (m_task_thread.joinable()) - m_task_thread.join(); + if (m_task_thread_0.joinable()) + m_task_thread_0.join(); + if (m_task_thread_1.joinable()) + m_task_thread_1.join(); } private: manager& m_tm; const std::chrono::milliseconds m_tick_interval; std::thread m_ticker_thread; - std::thread m_task_thread; + std::thread m_task_thread_0; + std::thread m_task_thread_1; std::atomic_flag m_stop; void From 1cebdee0cbb41f99e560240c42c9df0c4480f1d0 Mon Sep 17 00:00:00 2001 From: Joel Bodenmann Date: Mon, 10 Jun 2024 03:15:27 +0200 Subject: [PATCH 2/2] wip --- lib/timer.hpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/lib/timer.hpp b/lib/timer.hpp index 707bd58..1b25749 100644 --- a/lib/timer.hpp +++ b/lib/timer.hpp @@ -106,6 +106,7 @@ namespace jbo::timers std::mutex m_mutex; task_type task; + std::mutex task_mutex; std::chrono::milliseconds current; // ToDo: Should this be atomic? bool enabled = false; std::variant data; @@ -255,7 +256,10 @@ namespace jbo::timers t.arm(m_random_generator); // Push task - m_pending_tasks.emplace(t.task); + m_pending_tasks.emplace([f = t.task, mtx = &t.task_mutex]{ + std::scoped_lock lock(*mtx); + f(); + }); } } @@ -283,7 +287,8 @@ namespace jbo::timers } // Run task - task(); + if (task) + task(); } private: