From 698c285cb3ef6c016bbb08970a518cc36180bdac Mon Sep 17 00:00:00 2001 From: Sonullx Liu Date: Mon, 14 Sep 2020 18:11:49 +0800 Subject: [PATCH] Fix bugs in branch windows (#47) * fix: Fix the bug that LRUCache cannot work well when it is full * fix: Avoid possible division by zero crash --- src/manager/UpstreamManager.cc | 11 +++++++---- src/util/LRUCache.h | 25 ++++++++++--------------- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/src/manager/UpstreamManager.cc b/src/manager/UpstreamManager.cc index afce47e9..78d425d5 100644 --- a/src/manager/UpstreamManager.cc +++ b/src/manager/UpstreamManager.cc @@ -467,11 +467,13 @@ static inline bool __is_alive_or_group_alive(const UpstreamAddress *ua) const UpstreamAddress *Upstream::weighted_random_try_another() const { - if (available_weight_ == 0) + int temp_weight = available_weight_; + + if (temp_weight == 0) return NULL; const UpstreamAddress *ua = NULL; - int x = rand() % available_weight_; + int x = rand() % temp_weight; int s = 0; for (const auto *master : masters_) @@ -604,9 +606,10 @@ const UpstreamAddress *Upstream::get(const ParsedURI& uri) { int x = 0; int s = 0; + int temp_weight = total_weight_; - if (total_weight_ > 0) - x = rand() % total_weight_; + if (temp_weight > 0) + x = rand() % temp_weight; for (idx = 0; idx < n; idx++) { diff --git a/src/util/LRUCache.h b/src/util/LRUCache.h index bedc9a12..a665e10e 100644 --- a/src/util/LRUCache.h +++ b/src/util/LRUCache.h @@ -185,23 +185,18 @@ public: e->ref = 1; std::lock_guard lock(mutex_); - if (max_size_ == 0 || size_ < max_size_) + size_++; + e->in_cache = true; + e->ref++; + list_append(&in_use_, e); + MapIterator it = cache_map_.find(key); + if (it != cache_map_.end()) { - size_++; - e->in_cache = true; - e->ref++; - list_append(&in_use_, e); - MapIterator it = cache_map_.find(key); - if (it != cache_map_.end()) - { - erase_node(it->second); - it->second = e; - } - else - cache_map_[key] = e; + erase_node(it->second); + it->second = e; } - else//do not cache - e->next = NULL; + else + cache_map_[key] = e; if (max_size_ > 0) {