spawned_rt/threads/
mod.rs

1//! IO-threads based module to support shared behavior with task based version.
2
3pub mod mpsc;
4pub mod oneshot;
5
6use std::sync::{
7    atomic::{AtomicBool, Ordering},
8    Arc,
9};
10pub use std::{
11    future::Future,
12    thread::{sleep, spawn, JoinHandle},
13};
14
15use crate::{tasks::Runtime, tracing::init_tracing};
16
17pub fn run(f: fn()) {
18    init_tracing();
19
20    f()
21}
22
23pub fn block_on<F: Future>(future: F) -> F::Output {
24    let rt = Runtime::new().unwrap();
25    rt.block_on(future)
26}
27
28/// Spawn blocking is the same as spawn for pure threaded usage.
29pub fn spawn_blocking<F, R>(f: F) -> JoinHandle<R>
30where
31    F: FnOnce() -> R + Send + 'static,
32    R: Send + 'static,
33{
34    spawn(f)
35}
36
37#[derive(Clone, Debug, Default)]
38pub struct CancellationToken {
39    is_cancelled: Arc<AtomicBool>,
40}
41
42impl CancellationToken {
43    pub fn new() -> Self {
44        CancellationToken {
45            is_cancelled: Arc::new(false.into()),
46        }
47    }
48
49    pub fn is_cancelled(&mut self) -> bool {
50        self.is_cancelled.fetch_and(false, Ordering::SeqCst)
51    }
52
53    pub fn cancel(&mut self) {
54        self.is_cancelled.fetch_or(true, Ordering::SeqCst);
55    }
56}