C++实现令牌桶过滤算法
作者:野牛程序员:2023-12-28 18:31:25 C++阅读 2555
令牌桶过滤算法的C++实现如下:
#include <iostream> #include <chrono> #include <thread> #include <mutex> #include <condition_variable> class TokenBucketFilter { public: TokenBucketFilter(int capacity, int tokensPerSecond) : capacity_(capacity), tokensPerSecond_(tokensPerSecond) { tokens_ = capacity; lastRefillTime_ = std::chrono::steady_clock::now(); refillInterval_ = std::chrono::seconds(1) / tokensPerSecond_; } void refill() { std::unique_lock<std::mutex> lock(mutex_); auto now = std::chrono::steady_clock::now(); auto elapsedTime = now - lastRefillTime_; int tokensToAdd = static_cast<int>(elapsedTime / refillInterval_); tokens_ = std::min(capacity_, tokens_ + tokensToAdd); lastRefillTime_ = now; } bool tryConsume(int tokens) { std::unique_lock<std::mutex> lock(mutex_); refill(); if (tokens <= tokens_) { tokens_ -= tokens; return true; } else { return false; } } private: int capacity_; int tokensPerSecond_; int tokens_; std::chrono::steady_clock::time_point lastRefillTime_; std::chrono::steady_clock::duration refillInterval_; std::mutex mutex_; }; int main() { TokenBucketFilter tokenBucket(10, 5); // 10 tokens capacity, 5 tokens per second // Example usage for (int i = 0; i < 15; ++i) { if (tokenBucket.tryConsume(2)) { std::cout << "Consume successful. Remaining tokens: " << tokenBucket.tryConsume(2) << std::endl; } else { std::cout << "Consume failed. Wait for tokens to be available." << std::endl; } std::this_thread::sleep_for(std::chrono::milliseconds(200)); // Simulate some work } return 0; }
这是一个简单的C++实现,使用了互斥锁和条件变量确保线程安全。TokenBucketFilter
类维护了令牌桶的状态,包括桶的容量、每秒生成的令牌数、当前剩余的令牌数等。refill()
方法用于定期补充令牌,tryConsume()
方法尝试消耗指定数量的令牌。在主函数中,演示了如何使用令牌桶进行限流。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
- 上一篇:C语言中关于switch语句的理解
- 下一篇:什么是令牌桶过滤算法