diff --git a/src/jamidht/jamiaccount.cpp b/src/jamidht/jamiaccount.cpp index 058fe102d578833e2ff744078e1ff56f5127f35c..c11c3c2dfaf1a67c2a06282e102baf972553f7ad 100644 --- a/src/jamidht/jamiaccount.cpp +++ b/src/jamidht/jamiaccount.cpp @@ -304,7 +304,7 @@ JamiAccount::~JamiAccount() { shutdownConnections(); if (eventHandler) { - eventHandler->cancel(); + eventHandler->destroy(); eventHandler.reset(); } if(peerDiscovery_){ @@ -3091,17 +3091,17 @@ JamiAccount::getLastMessages(const uint64_t& base_timestamp) void JamiAccount::checkPendingCallsTask() { - bool hasHandler = eventHandler and not eventHandler->isCancelled(); - if (not pendingCalls_.empty() and not hasHandler) { - eventHandler = Manager::instance().scheduler().scheduleAtFixedRate([w = weak()] { + decltype(eventHandler) handler; + if (not pendingCalls_.empty()) { + handler = Manager::instance().scheduler().scheduleAtFixedRate([w = weak()] { if (auto this_ = w.lock()) return this_->handlePendingCallList(); return false; }, std::chrono::milliseconds(10)); - } else if (pendingCalls_.empty() and hasHandler) { - eventHandler->cancel(); - eventHandler.reset(); } + std::swap(handler, eventHandler); + if (handler) + handler->cancel(); } void diff --git a/src/scheduled_executor.h b/src/scheduled_executor.h index 2536b256fdfcc12b1fe889c0be58f661d0391b9c..d4acbe7e832d540ba0ffd8a0e709df71cb81c045 100644 --- a/src/scheduled_executor.h +++ b/src/scheduled_executor.h @@ -68,22 +68,28 @@ public: RepeatedTask(RepeatedJob&& j) : job_(std::move(j)) {} bool run() { std::lock_guard<std::mutex> l(lock_); - if (job_ and not job_()) + if (cancel_.load() or (job_ and not job_())) { + cancel_.store(true); job_ = {}; + } return (bool)job_; } void cancel() { + cancel_.store(true); + } + void destroy() { + cancel(); std::lock_guard<std::mutex> l(lock_); job_ = {}; } bool isCancelled() const { - std::lock_guard<std::mutex> l(lock_); - return !job_; + return cancel_.load(); } private: NON_COPYABLE(RepeatedTask); - RepeatedJob job_; mutable std::mutex lock_; + RepeatedJob job_; + std::atomic_bool cancel_ {false}; }; class ScheduledExecutor {