mirror of
https://github.com/Zygo/bees.git
synced 2025-05-17 21:35:45 +02:00
time: separate sleep time calculation from sleep_for method
We need to replace nanosleeps with condition variables so that we can implement BeesContext::stop. Export the time calculation from sleep_for() into a new method called sleep_time(). If the thread executing RateLimiter::sleep_for() is interrupted, it will no longer be able to restart, as the sleep_time() method is destructive. This calls for further refactoring of sleep_time() into destructive and non-destructive parts; however, there are currently no users of sleep_for() which rely on being able to restart after being interrupted by a signal. Signed-off-by: Zygo Blaxell <bees@furryterror.org>
This commit is contained in:
parent
0e42c75f5a
commit
cbc6725f0f
@ -42,6 +42,7 @@ namespace crucible {
|
|||||||
RateLimiter(double rate, double burst);
|
RateLimiter(double rate, double burst);
|
||||||
RateLimiter(double rate);
|
RateLimiter(double rate);
|
||||||
void sleep_for(double cost = 1.0);
|
void sleep_for(double cost = 1.0);
|
||||||
|
double sleep_time(double cost = 1.0);
|
||||||
bool is_ready();
|
bool is_ready();
|
||||||
void borrow(double cost = 1.0);
|
void borrow(double cost = 1.0);
|
||||||
};
|
};
|
||||||
|
31
lib/time.cc
31
lib/time.cc
@ -116,23 +116,26 @@ namespace crucible {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
double
|
||||||
|
RateLimiter::sleep_time(double cost)
|
||||||
|
{
|
||||||
|
borrow(cost);
|
||||||
|
unique_lock<mutex> lock(m_mutex);
|
||||||
|
update_tokens();
|
||||||
|
if (m_tokens >= 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return -m_tokens / m_rate;
|
||||||
|
}
|
||||||
|
|
||||||
void
|
void
|
||||||
RateLimiter::sleep_for(double cost)
|
RateLimiter::sleep_for(double cost)
|
||||||
{
|
{
|
||||||
borrow(cost);
|
double time_to_sleep = sleep_time(cost);
|
||||||
while (1) {
|
if (time_to_sleep > 0.0) {
|
||||||
unique_lock<mutex> lock(m_mutex);
|
nanosleep(time_to_sleep);
|
||||||
update_tokens();
|
} else {
|
||||||
if (m_tokens >= 0) {
|
return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
double sleep_time(-m_tokens / m_rate);
|
|
||||||
lock.unlock();
|
|
||||||
if (sleep_time > 0.0) {
|
|
||||||
nanosleep(sleep_time);
|
|
||||||
} else {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user