CppCommon  1.0.4.1
C++ Common Library
algorithms_token_bucket.cpp

Token bucket rate limit algorithm example

#include "threads/thread.h"
#include "time/timestamp.h"
#include <atomic>
#include <iostream>
int main(int argc, char** argv)
{
std::cout << "Press Enter to stop..." << std::endl;
// Token bucket with one token per second rate and ten burst tokens
std::atomic<bool> stop(false);
std::thread worker = std::thread([&stop, &tb]()
{
while (!stop)
{
if (tb.Consume())
std::cout << (CppCommon::UtcTimestamp().seconds() % 60) << " - Token consumed" << std::endl;
else
}
});
// Wait for input
std::cin.get();
// Stop the worker thread
stop = true;
// Wait for the worker thread
worker.join();
return 0;
}
static void Yield() noexcept
Yield to other threads.
Definition: thread.cpp:143
uint64_t seconds() const noexcept
Get total seconds of the current timestamp.
Definition: timestamp.h:143
Token bucket rate limit algorithm.
Definition: token_bucket.h:34
bool Consume(uint64_t tokens=1)
Try to consume the given count of tokens.
UTC timestamp.
Definition: timestamp.h:248
Thread definition.
Timestamp definition.
Token bucket rate limit algorithm definition.