simple/simple.rs
1use arl::RateLimiter;
2use std::sync::{Arc, Mutex};
3use std::thread::sleep;
4use std::time::Duration;
5
6#[tokio::main]
7async fn main() {
8 // Limit rate to 10 times in 2 seconds.
9 let limiter = RateLimiter::new(10, Duration::from_secs(2));
10 let counter = Arc::new(Mutex::new(0));
11 // Spawn 4 threads.
12 for i in 0..4 {
13 // RateLimiter can be cloned - all threads will use the same timer/stats underneath.
14 let limiter = limiter.clone();
15 let counter = counter.clone();
16 tokio::spawn(async move {
17 // Do things in a loop. Notice there is no `sleep` in here.
18 loop {
19 // Wait if needed. First 10 will be executed immediately.
20 limiter.wait().await;
21 // Increment and show counter just for fun.
22 let mut c = counter.lock().unwrap();
23 *c += 1;
24 println!("Counter: {} by thread #{}", c, i);
25 }
26 });
27 }
28 // Let other threads do some work.
29 sleep(Duration::from_secs(21));
30}