1use std::{sync::Arc, time::Duration};
2
3pub struct Statis {
4 _rt: std::thread::JoinHandle<()>,
5 sum: Arc<std::sync::atomic::AtomicU64>,
6}
7
8impl Statis {
9 pub fn new<P: Fn(u64) + Send + 'static>(print: P) -> Self {
10 let sum = Arc::new(std::sync::atomic::AtomicU64::new(0));
11 let sum_clone = sum.clone();
12 let rt = std::thread::spawn(move || loop {
13 std::thread::sleep(Duration::from_millis(1000));
14 let v = sum_clone.fetch_and(0, std::sync::atomic::Ordering::SeqCst);
15 if v > 0 {
16 print(v);
17 }
18 });
19 Self { _rt: rt, sum }
20 }
21
22 pub fn add(&self) {
23 _ = self.sum.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
24 }
25}
26
27impl Drop for Statis {
28 fn drop(&mut self) {}
29}
30
31#[test]
32fn test() {
33 pub static RECKON_BY_SEC: once_cell::sync::Lazy<Statis> =
34 once_cell::sync::Lazy::new(|| Statis::new(|v| println!("one sec run sum: {v}")));
35
36 let rt = std::thread::spawn(|| {
37 for i in 0..10000_0000 {
38 RECKON_BY_SEC.add();
39 }
40 });
41 let rt2 = std::thread::spawn(|| {
42 for i in 0..10000_0000 {
43 RECKON_BY_SEC.add();
44 }
45 });
46 let rt3 = std::thread::spawn(|| {
47 for i in 0..10000_0000 {
48 RECKON_BY_SEC.add();
49 }
50 });
51
52 rt.join();
53 rt2.join();
54 rt3.join();
55}