Skip to content

Commit 82cf041

Browse files
author
Stjepan Glavina
committed
Add a fairness example
1 parent d4bf926 commit 82cf041

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

examples/fairness.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//! Demonstrates fairness properties of the lock.
2+
//!
3+
//! A number of threads run a loop in which they hold the lock for a little bit and re-acquire it
4+
//! immediately after. In the end we print the number of times each thread acquired the lock.
5+
6+
use std::thread;
7+
use std::time::{Duration, Instant};
8+
9+
use async_lock::Lock;
10+
use smol::Timer;
11+
12+
fn main() {
13+
let num_threads = 30;
14+
let mut threads = Vec::new();
15+
let hits = Lock::new(vec![0; num_threads]);
16+
17+
for i in 0..num_threads {
18+
let hits = hits.clone();
19+
threads.push(thread::spawn(move || {
20+
smol::run(async {
21+
let start = Instant::now();
22+
23+
while start.elapsed() < Duration::from_secs(1) {
24+
let mut hits = hits.lock().await;
25+
hits[i] += 1;
26+
Timer::after(Duration::from_micros(5000)).await;
27+
}
28+
})
29+
}));
30+
}
31+
32+
for t in threads {
33+
t.join().unwrap();
34+
}
35+
36+
dbg!(hits);
37+
}

0 commit comments

Comments
 (0)