Skip to main content

radicle_node/runtime/
thread.rs

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