radicle_node/runtime/
thread.rs

1use std::thread;
2
3pub use thread::*;
4
5use radicle::prelude::NodeId;
6
7/// Spawn an OS thread.
8pub fn spawn<D, F, T>(nid: &NodeId, label: D, f: F) -> thread::JoinHandle<T>
9where
10    D: std::fmt::Display,
11    F: FnOnce() -> T,
12    F: Send + 'static,
13    T: Send + 'static,
14{
15    thread::Builder::new()
16        .name(name(nid, label))
17        .spawn(f)
18        .expect("thread::spawn: thread label must not contain NULL bytes")
19}
20
21/// Spawn a scoped OS thread.
22pub fn spawn_scoped<'scope, 'env, D, F, T>(
23    nid: &NodeId,
24    label: D,
25    scope: &'scope thread::Scope<'scope, 'env>,
26    f: F,
27) -> thread::ScopedJoinHandle<'scope, T>
28where
29    D: std::fmt::Display,
30    F: FnOnce() -> T,
31    F: Send + 'scope,
32    T: Send + 'scope,
33{
34    thread::Builder::new()
35        .name(name(nid, label))
36        .spawn_scoped(scope, f)
37        .expect("thread::spawn_scoped: thread label must not contain NULL bytes")
38}
39
40pub fn name<D: std::fmt::Display>(nid: &NodeId, label: D) -> String {
41    if cfg!(debug_assertions) {
42        format!("{nid} {:<14}", format!("<{label}>"))
43    } else {
44        format!("{label}")
45    }
46}