From 8395e821fc1af93d1511bb914bc5448bde262b1c Mon Sep 17 00:00:00 2001 From: Tao He Date: Mon, 24 Oct 2022 10:07:53 +0800 Subject: [PATCH] Protect the timer to avoid "cancel" and "refresh" happens at the same time. Signed-off-by: Tao He --- etcd/KeepAlive.hpp | 4 ++++ src/KeepAlive.cpp | 2 ++ 2 files changed, 6 insertions(+) diff --git a/etcd/KeepAlive.hpp b/etcd/KeepAlive.hpp index 36b586f..f7ea1d3 100644 --- a/etcd/KeepAlive.hpp +++ b/etcd/KeepAlive.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -117,6 +118,9 @@ namespace etcd int ttl; int64_t lease_id; + + // protect the initializing status of `timer`. + std::mutex mutex_for_refresh_; std::atomic_bool continue_next; // grpc timeout in `refresh()` diff --git a/src/KeepAlive.cpp b/src/KeepAlive.cpp index 0d71cb9..43ca87e 100644 --- a/src/KeepAlive.cpp +++ b/src/KeepAlive.cpp @@ -124,6 +124,7 @@ etcd::KeepAlive::~KeepAlive() void etcd::KeepAlive::Cancel() { + std::lock_guard scope_lock(mutex_for_refresh_); if (!continue_next.exchange(false)) { return; } @@ -142,6 +143,7 @@ void etcd::KeepAlive::Check() { void etcd::KeepAlive::refresh() { + std::lock_guard scope_lock(mutex_for_refresh_); if (!continue_next.load()) { return; }