← 返回 uber 的题目列表Thread-safe Token Bucket Rate Limiter
类型:online_judge
Problem: Thread-safe Token Bucket Rate Limiter
Design and implement a thread-safe rate limiter using the Token Bucket algorithm.
Requirements
Use the Token Bucket algorithm.
Support concurrent calls from multiple threads and guarantee atomic token accounting and distribution.
Discuss how to reduce lock contention under high concurrency.
API
Implement:
allow(now: float, cost: int = 1) -> bool
Meaning: at time now, try to consume cost tokens. Return True if enough tokens are available; otherwise return False.
Input Format
For deterministic judging, logical time is provided:
First line: capacity refill_rate, where capacity is bucket capacity and refill_rate is tokens added per second.
Second line: integer m, number of operations.
Next m lines: ALLOW now cost
Output Format
For each ALLOW, print one line: true or false.
Constraints
1 <= capacity <= 10^9
0 < refill_rate <= 10^9
1 <= m <= 200000
now is non-decreasing.
Example
Input
5 1
6
ALLOW 0 1
ALLOW 0 1
ALLOW 0 1
ALLOW 0 1
ALLOW 0 1
ALLOW 0 1
Output
true
true
true
true
true
false