Move mutex to rate_limiter

This commit is contained in:
Piotr Wójcik 2024-09-11 13:18:08 +02:00
commit 536ae7a91f
2 changed files with 3 additions and 6 deletions

View file

@ -16,7 +16,6 @@ nano::rate::token_bucket::token_bucket (std::size_t max_token_count_a, std::size
bool nano::rate::token_bucket::try_consume (unsigned tokens_required_a)
{
debug_assert (tokens_required_a <= 1e9);
nano::lock_guard<nano::mutex> guard{ mutex };
refill ();
bool possible = current_size >= tokens_required_a;
if (possible)
@ -48,14 +47,11 @@ void nano::rate::token_bucket::refill ()
std::size_t nano::rate::token_bucket::largest_burst () const
{
nano::lock_guard<nano::mutex> guard{ mutex };
return max_token_count - smallest_size;
}
void nano::rate::token_bucket::reset (std::size_t max_token_count_a, std::size_t refill_rate_a)
{
nano::lock_guard<nano::mutex> guard{ mutex };
// A token count of 0 indicates unlimited capacity. We use 1e9 as
// a sentinel, allowing largest burst to still be computed.
if (max_token_count_a == 0 || refill_rate_a == 0)
@ -78,10 +74,12 @@ nano::rate_limiter::rate_limiter (std::size_t limit_a, double burst_ratio_a) :
bool nano::rate_limiter::should_pass (std::size_t message_size_a)
{
nano::lock_guard<nano::mutex> guard{ mutex };
return bucket.try_consume (nano::narrow_cast<unsigned int> (message_size_a));
}
void nano::rate_limiter::reset (std::size_t limit_a, double burst_ratio_a)
{
nano::lock_guard<nano::mutex> guard{ mutex };
bucket.reset (static_cast<std::size_t> (limit_a * burst_ratio_a), limit_a);
}

View file

@ -54,8 +54,6 @@ private:
std::size_t smallest_size{ 0 };
std::chrono::steady_clock::time_point last_refill;
mutable nano::mutex mutex;
static std::size_t constexpr unlimited_rate_sentinel{ static_cast<std::size_t> (1e9) };
};
}
@ -73,5 +71,6 @@ public:
private:
nano::rate::token_bucket bucket;
mutable nano::mutex mutex;
};
}