devela/work/process/thread/
ext.rs

1// devela::work::process::thread::ext
2//
3//! Defines the [`ExtThread`] trait.
4//
5
6use crate::{Duration, Thread, ThreadJoinHandle, ThreadScope};
7use std::thread::{
8    available_parallelism, current, panicking, park, park_timeout, scope, sleep, spawn, yield_now,
9};
10
11/// Marker trait to prevent downstream implementations of the [`ExtThread`] trait.
12trait Sealed {}
13impl Sealed for Thread {}
14
15#[doc = crate::TAG_NAMESPACE!()]
16/// Extension trait providing additional methods for [`Thread`]s.
17///
18/// It offers the standalone functions in `std::thread` as associated methods.
19#[rustfmt::skip]
20#[cfg_attr(feature = "nightly_doc", doc(notable_trait))]
21#[expect(private_bounds, reason = "Sealed")]
22pub trait ExtThread: Sealed {
23    /// Gets a handle to the thread that invokes it.
24    ///
25    /// See `std::thread::`[current].
26    #[must_use]
27    fn current() -> Thread { current() }
28
29    /// Determines whether the current thread is unwinding because of panic.
30    ///
31    /// See `std::thread::`[panicking].
32    #[must_use]
33    fn panicking() -> bool { panicking() }
34
35    /// Returns an estimate of the default amount of parallelism a program should use.
36    ///
37    /// See `std::thread::`[available_parallelism].
38    fn parallelism() ->  Result<usize, crate::IoError> {
39        available_parallelism().map(|n|n.get())
40    }
41
42    /// Blocks unless or until the current thread’s token is made available.
43    ///
44    /// See `std::thread::`[park].
45    fn park() { park() }
46
47    /// Blocks unless or until the current thread’s token is made available
48    /// or the specified duration has been reached (may wake spuriously).
49    ///
50    /// See `std::thread::`[park_timeout].
51    fn park_timeout(duration: Duration) { park_timeout(duration) }
52
53    /// Create a scope for spawning scoped threads.
54    ///
55    /// See `std::thread::`[scope].
56    fn scope<'env, F, T>(f: F) -> T
57    where F: for<'scope> FnOnce(&'scope ThreadScope<'scope, 'env>) -> T { scope(f) }
58
59    /// Puts the current thread to sleep for at least the specified amount of time.
60    ///
61    /// See `std::thread::`[sleep].
62    fn sleep(duration: Duration) { sleep(duration) }
63
64    /// Spawns a new thread, returning a [`ThreadJoinHandle`] for it.
65    ///
66    /// See `std::thread::`[spawn].
67    fn spawn<F, T>(f: F) -> ThreadJoinHandle<T>
68    where F: FnOnce() -> T + Send + 'static, T: Send + 'static { spawn(f) }
69
70    /// Cooperatively gives up a timeslice to the OS scheduler.
71    ///
72    /// See `std::thread::`[yield_now].
73    fn yield_now() { yield_now() }
74}
75impl ExtThread for Thread {}