diff --git a/include/crucible/time.h b/include/crucible/time.h index 7261013..cad7fe3 100644 --- a/include/crucible/time.h +++ b/include/crucible/time.h @@ -42,6 +42,7 @@ namespace crucible { RateLimiter(double rate, double burst); RateLimiter(double rate); void sleep_for(double cost = 1.0); + double sleep_time(double cost = 1.0); bool is_ready(); void borrow(double cost = 1.0); }; diff --git a/lib/time.cc b/lib/time.cc index 77a99ad..99001b6 100644 --- a/lib/time.cc +++ b/lib/time.cc @@ -116,23 +116,26 @@ namespace crucible { } } + double + RateLimiter::sleep_time(double cost) + { + borrow(cost); + unique_lock lock(m_mutex); + update_tokens(); + if (m_tokens >= 0) { + return 0; + } + return -m_tokens / m_rate; + } + void RateLimiter::sleep_for(double cost) { - borrow(cost); - while (1) { - unique_lock lock(m_mutex); - update_tokens(); - if (m_tokens >= 0) { - return; - } - double sleep_time(-m_tokens / m_rate); - lock.unlock(); - if (sleep_time > 0.0) { - nanosleep(sleep_time); - } else { - return; - } + double time_to_sleep = sleep_time(cost); + if (time_to_sleep > 0.0) { + nanosleep(time_to_sleep); + } else { + return; } }