fast_able/
thread_channel.rs

1use std::{
2    sync::mpsc::{SendError, Sender},
3    thread::{self, JoinHandle},
4};
5
6/// A channel that processes messages in a dedicated thread
7/// 在专用线程中处理消息的通道
8pub struct ThreadChannel<T> {
9    _join: JoinHandle<()>,
10    sender: Sender<T>,
11}
12
13unsafe impl<T> Send for ThreadChannel<T> {}
14unsafe impl<T> Sync for ThreadChannel<T> {}
15
16impl<T: Send + 'static> ThreadChannel<T> {
17    /// Create a new ThreadChannel
18    /// 创建一个新的 ThreadChannel
19    pub fn new(call: impl Fn(T) + Send + 'static) -> Self {
20        let (sender, recev) = std::sync::mpsc::channel();
21        ThreadChannel {
22            sender,
23            _join: thread::spawn(move || {
24                while let Ok(v) = recev.recv() {
25                    call(v);
26                }
27            }),
28        }
29    }
30    /// Send a message to the channel
31    /// 发送消息到通道
32    pub fn send(&self, v: T) -> Result<(), SendError<T>> {
33        self.sender.send(v)
34    }
35}
36
37#[test]
38fn test() {
39    use crate::static_type_std::StaticTypeForStd;
40    
41    static S: StaticTypeForStd<ThreadChannel<i32>> = StaticTypeForStd::new(|| {
42        ThreadChannel::new(|v| {
43            println!("print out: {v}");
44        })
45    });
46
47    S.init_static();
48
49    S.send(1);
50    S.send(2);
51    S.send(3);
52    S.send(4);
53    std::thread::sleep(std::time::Duration::from_secs(3));
54}