thread_spawn_critical.rs

Overview

This file defines and implements the SpawnCritical trait, which extends the functionality of std::thread::Builder to spawn threads that run critical tasks. The key feature of these critical threads is that if the thread's closure returns an error, the program logs the error and immediately terminates the entire process with a specific exit code. This approach ensures that critical failures in spawned threads do not go unnoticed or unhandled silently.

The trait provides two methods:

The implementation uses anyhow::Result for error handling and tracing for logging, integrating with existing error and logging infrastructure.


Trait: SpawnCritical

The SpawnCritical trait defines two methods to spawn threads that run critical tasks:

pub trait SpawnCritical {
    fn spawn_critical<F, T>(self, f: F) -> std::io::Result<std::thread::JoinHandle<T>>
    where
        F: FnOnce() -> anyhow::Result<T> + Send + 'static,
        T: Send + 'static;

    fn spawn_scoped_critical<'scope, 'env, F, T>(
        self,
        scope: &'scope std::thread::Scope<'scope, 'env>,
        f: F,
    ) -> std::io::Result<std::thread::ScopedJoinHandle<'scope, T>>
    where
        F: FnOnce() -> anyhow::Result<T> + Send + 'scope,
        T: Send + 'scope;
}

spawn_critical

use std::thread;

let builder = thread::Builder::new().name("critical_thread".into());
let handle = builder.spawn_critical(|| {
    // Critical code here
    if something_went_wrong {
        Err(anyhow::anyhow!("Something failed"))
    } else {
        Ok(42)
    }
})?;
let result = handle.join().unwrap();

spawn_scoped_critical

std::thread::scope(|scope| {
    let builder = std::thread::Builder::new().name("scoped_critical".into());
    let handle = builder.spawn_scoped_critical(scope, || {
        // Critical scoped code
        Ok("done")
    })?;
    let result = handle.join().unwrap();
    Ok::<(), std::io::Error>(())
});

Implementation Details

The trait SpawnCritical is implemented for std::thread::Builder, effectively extending the builder API with critical thread spawning capabilities.

Error Handling and Process Termination

The choice of exit code 101 is a fixed indicator representing a critical thread failure.

Thread Naming and Logging

Lifetimes and Thread Safety


Interaction with the System


Mermaid Diagram

classDiagram
class SpawnCritical {
+spawn_critical()
+spawn_scoped_critical()
}
class std::thread::Builder {
+spawn()
+spawn_scoped()
}
SpawnCritical <|.. std::thread::Builder
%% Method behavior
class SpawnCriticalMethods {
<<interface>>
+call closure f() -> Result<T>
+on Ok: return value
+on Err: log error, exit(101)
}
SpawnCriticalMethods <|-- SpawnCritical

This diagram shows the relationship between the SpawnCritical trait and std::thread::Builder, highlighting the two main methods and their critical error handling behavior.