st/
main.rs

1use std::{
2    io::Write,
3    time::{Duration, Instant},
4};
5
6use rand::seq::SliceRandom;
7
8#[allow(dead_code)]
9fn jointest() {
10    let threads = (0..4).into_iter().map(|j| {
11        std::thread::spawn(move || {
12            const MAX_TRIALS: u32 = 40;
13            for i in 0..MAX_TRIALS {
14                println!("trial {}/{}", i * j, MAX_TRIALS * j);
15                let mut threads = (0..4)
16                    .into_iter()
17                    .map(|_| {
18                        std::thread::spawn(move || {
19                            let delay = rand::random::<u32>() % 100_000;
20                            if delay > 10_000 {
21                                std::thread::sleep(Duration::from_nanos(delay as u64));
22                            }
23                        })
24                    })
25                    .collect::<Vec<_>>();
26                threads.shuffle(&mut rand::thread_rng());
27                for th in threads {
28                    th.join().unwrap();
29                }
30            }
31        })
32    });
33    for th in threads {
34        th.join().unwrap();
35    }
36}
37
38fn main() {
39    //jointest();
40    //return;
41    let threads = (0..4)
42        .into_iter()
43        .map(|i| std::thread::spawn(move || thread_main(i)))
44        .collect::<Vec<_>>();
45    for th in threads {
46        th.join().unwrap();
47    }
48    println!()
49}
50
51fn thread_main(num: u32) {
52    let start = Instant::now();
53    for _n in 0..5 {
54        let mut sum = 0;
55        for i in 0..1_000_000_000 {
56            sum += i;
57            if i % 10_000_000 == 0 && false {
58                unsafe {
59                    print!("{}", char::from_u32_unchecked(b'a' as u32 + num));
60                }
61                std::io::stdout().flush().unwrap();
62            }
63            sum = std::hint::black_box(sum);
64        }
65        std::hint::black_box(sum);
66    }
67    println!(
68        "thread {} in {}ms",
69        num,
70        (Instant::now() - start).as_millis()
71    );
72}