fast_able/
statis.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use std::{sync::Arc, time::Duration};

pub struct Statis {
    _rt: std::thread::JoinHandle<()>,
    sum: Arc<std::sync::atomic::AtomicU64>,
}

impl Statis {
    pub fn new<P: Fn(u64) + Send + 'static>(print: P) -> Self {
        let sum = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let sum_clone = sum.clone();
        let rt = std::thread::spawn(move || loop {
            std::thread::sleep(Duration::from_millis(1000));
            let v = sum_clone.fetch_and(0, std::sync::atomic::Ordering::SeqCst);
            if v > 0 {
                print(v);
            }
        });
        Self { _rt: rt, sum }
    }

    pub fn add(&self) {
        _ = self.sum.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    }
}

impl Drop for Statis {
    fn drop(&mut self) {}
}

#[test]
fn test() {
    pub static RECKON_BY_SEC: once_cell::sync::Lazy<Statis> =
        once_cell::sync::Lazy::new(|| Statis::new(|v| println!("one sec run sum: {v}")));

    let rt = std::thread::spawn(|| {
        for i in 0..10000_0000 {
            RECKON_BY_SEC.add();
        }
    });
    let rt2 = std::thread::spawn(|| {
        for i in 0..10000_0000 {
            RECKON_BY_SEC.add();
        }
    });
    let rt3 = std::thread::spawn(|| {
        for i in 0..10000_0000 {
            RECKON_BY_SEC.add();
        }
    });

    rt.join();
    rt2.join();
    rt3.join();
}