preempt_rt/thread.rs
1use crate::sched::{IntoSchedParams, Scheduler};
2use std::thread;
3
4/// Spawn a thread with the provided scheduler and params.
5///
6/// Params can either be a SchedParams struct, or an i32 representing the desired priority.
7/// This function validates that the priority is between min and max for the scheduler before
8/// attempting to set it. It panics if the priority is outside the allowed range or setting the
9/// scheduler returns an error code.
10pub fn spawn<F, T>(
11 scheduler: Scheduler,
12 params: impl IntoSchedParams,
13 f: F,
14) -> thread::JoinHandle<T>
15where
16 F: FnOnce() -> T,
17 F: Send + 'static,
18 T: Send + 'static,
19{
20 try_spawn(scheduler, params, move |set_result| {
21 set_result.expect("failed to set scheduler");
22 f()
23 })
24}
25
26/// Spawn a thread and attempt to set the schedule of the current thread. The result of setting
27/// the scheduler is provided to the thread closure as an argument.
28///
29/// Params can either be a SchedParams struct, or an i32 representing the desired priority.
30/// This function validates that the priority is between min and max for the scheduler before
31/// attempting to set it. Failures will continue execution and pass through the Result to the
32/// thread closure.
33#[cfg(target_os = "linux")]
34pub fn try_spawn<F, T>(
35 scheduler: Scheduler,
36 params: impl IntoSchedParams,
37 f: F,
38) -> thread::JoinHandle<T>
39where
40 F: FnOnce(crate::sched::RtResult<()>) -> T,
41 F: Send + 'static,
42 T: Send + 'static,
43{
44 let params = params.into_sched_params();
45 thread::spawn(move || {
46 let set_result = scheduler
47 .with_params(params)
48 .and_then(|ps| ps.set_current());
49 f(set_result)
50 })
51}
52
53/// Spawn a thread and attempt to set the schedule of the current thread. The result of setting
54/// the scheduler is provided to the thread closure as an argument.
55///
56/// Params can either be a SchedParams struct, or an i32 representing the desired priority.
57/// This function validates that the priority is between min and max for the scheduler before
58/// attempting to set it. Failures will continue execution and pass through the Result to the
59/// thread closure.
60///
61/// This is a stub version of the function that always passes PreemptRtError::NonLinuxPlatform
62/// to the thread closure.
63#[cfg(all(feature = "non-linux-stubs", target_os = "macos"))]
64pub fn try_spawn<F, T>(
65 _scheduler: Scheduler,
66 _params: impl IntoSchedParams,
67 f: F,
68) -> thread::JoinHandle<T>
69where
70 F: FnOnce(crate::sched::RtResult<()>) -> T,
71 F: Send + 'static,
72 T: Send + 'static,
73{
74 thread::spawn(move || f(Err(crate::sched::PreemptRtError::NonLinuxPlatform("macos"))))
75}