File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments