fast_able/
thread_channel.rs

1use std::{
2    sync::mpsc::{SendError, Sender},
3    thread::{self, JoinHandle},
4};
5
6pub struct ThreadChannel<T> {
7    _join: JoinHandle<()>,
8    sender: Sender<T>,
9}
10
11unsafe impl<T> Send for ThreadChannel<T> {}
12unsafe impl<T> Sync for ThreadChannel<T> {}
13
14impl<T: Send + 'static> ThreadChannel<T> {
15    pub fn new(call: impl Fn(T) + Send + 'static) -> Self {
16        let (sender, recev) = std::sync::mpsc::channel();
17        ThreadChannel {
18            sender,
19            _join: thread::spawn(move || {
20                while let Ok(v) = recev.recv() {
21                    call(v);
22                }
23            }),
24        }
25    }
26    pub fn send(&self, v: T) -> Result<(), SendError<T>> {
27        self.sender.send(v)
28    }
29}
30
31#[test]
32fn test() {
33    use crate::static_type_std::StaticTypeForStd;
34    
35    static S: StaticTypeForStd<ThreadChannel<i32>> = StaticTypeForStd::new(|| {
36        ThreadChannel::new(|v| {
37            println!("print out: {v}");
38        })
39    });
40
41    S.init_static();
42
43    S.send(1);
44    S.send(2);
45    S.send(3);
46    S.send(4);
47    std::thread::sleep(std::time::Duration::from_secs(3));
48}