fast_able/
thread_channel.rs1use std::{
2 sync::mpsc::{SendError, Sender},
3 thread::{self, JoinHandle},
4};
5
6pub 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 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 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}