lifetime_thread/
lib.rs

1#![deny(
2    warnings,
3    clippy::all,
4    clippy::correctness,
5    clippy::style,
6    clippy::complexity,
7    clippy::perf,
8    clippy::pedantic,
9    clippy::nursery,
10    clippy::cargo
11)]
12use crossbeam_epoch::Atomic;
13use std::{future::Future, thread};
14mod inner;
15pub use inner::Inner;
16
17mod outer;
18pub use outer::Outer;
19
20/// Spawns a new thread, return `data` warpped in `Outer`
21pub fn spawn<T, F>(data: T, f: F) -> Outer<T>
22where
23    T: Send + 'static,
24    F: FnOnce(Inner<T>) + Send + 'static,
25{
26    let flag_ptr = Box::into_raw(Box::new(Atomic::new(0b11_u8))) as usize;
27    let data_ptr = Box::into_raw(Box::new(data)) as usize;
28    let inner = Inner::new(flag_ptr, data_ptr);
29    thread::spawn(move || f(inner));
30    Outer::new(flag_ptr, data_ptr)
31}
32
33/// Spawns a new async task, return `data` warpped in `Outer`
34pub fn async_spawn<T, F, FU>(data: T, f: F) -> Outer<T>
35where
36    T: Send + 'static,
37    FU: Future<Output = ()> + Send + 'static,
38    F: FnOnce(Inner<T>) -> FU + Send + 'static,
39{
40    let flag_ptr = Box::into_raw(Box::new(Atomic::new(0b11_u8))) as usize;
41    let data_ptr = Box::into_raw(Box::new(data)) as usize;
42    let inner = Inner::new(flag_ptr, data_ptr);
43    tokio::spawn(async { f(inner).await });
44    Outer::new(flag_ptr, data_ptr)
45}