From 7095f4668cbb7680ba7a8ab80c3f5e08061eefea Mon Sep 17 00:00:00 2001 From: WarmUpTill Date: Tue, 1 Mar 2022 20:00:59 +0100 Subject: [PATCH] Rework wait action to support being interrupted by calling Stop() --- src/headers/macro.hpp | 2 +- src/macro-action-wait.cpp | 24 +++++++++++++++--------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/headers/macro.hpp b/src/headers/macro.hpp index 4137320d..ed9bbbb9 100644 --- a/src/headers/macro.hpp +++ b/src/headers/macro.hpp @@ -89,7 +89,7 @@ public: int GetCount() { return _count; }; void ResetCount() { _count = 0; }; bool GetStop() { return _stop; } - void Stop() { _stop = true; } + void Stop(); std::deque> &Conditions() { return _conditions; diff --git a/src/macro-action-wait.cpp b/src/macro-action-wait.cpp index 44e6ad22..989f1ebe 100644 --- a/src/macro-action-wait.cpp +++ b/src/macro-action-wait.cpp @@ -21,9 +21,9 @@ static std::default_random_engine re(rd()); bool MacroActionWait::PerformAction() { - double sleep_duration; + double sleepDuration; if (_waitType == WaitType::FIXED) { - sleep_duration = _duration.seconds; + sleepDuration = _duration.seconds; } else { double min = (_duration.seconds < _duration2.seconds) ? _duration.seconds @@ -32,17 +32,23 @@ bool MacroActionWait::PerformAction() ? _duration2.seconds : _duration.seconds; std::uniform_real_distribution unif(min, max); - sleep_duration = unif(re); + sleepDuration = unif(re); } vblog(LOG_INFO, "perform action wait with duration of %f", - sleep_duration); + sleepDuration); - std::unique_lock lock(switcher->m); + auto time = std::chrono::high_resolution_clock::now() + + std::chrono::milliseconds((int)(sleepDuration * 1000)); + auto macro = GetMacro(); switcher->abortMacroWait = false; - switcher->macroWaitCv.wait_for( - lock, - std::chrono::milliseconds((long long)(sleep_duration * 1000)), - [] { return switcher->abortMacroWait.load(); }); + std::unique_lock lock(switcher->m); + while (!switcher->abortMacroWait && !macro->GetStop()) { + if (switcher->macroWaitCv.wait_until(lock, time) == + std::cv_status::timeout) { + break; + } + } + return !switcher->abortMacroWait; }