Skip to main content

Thread

Trait Thread 

Source
pub trait Thread: Runnable {
    // Required methods
    fn start(self) -> JoinHandle<Self::Output>;
    fn start_with_builder(self, builder: Builder) -> JoinHandle<Self::Output>;
}
Expand description

An extension trait that provides a method to spawn a thread for a Runnable task.

This trait is automatically implemented for any type that implements Runnable. You do not need to implement this trait manually.

Required Methods§

Source

fn start(self) -> JoinHandle<Self::Output>

Spawns a new standard library thread to execute the run method.

This acts as a zero-cost abstraction over std::thread::spawn.

§Returns

Returns a std::thread::JoinHandle that can be used to wait for the thread to finish and extract its Output.

§Examples
use struct_threads::{Runnable, Thread};

struct MathTask(i32, i32);

impl Runnable for MathTask {
    type Output = i32;
    fn run(self) -> Self::Output {
        self.0 + self.1
    }
}

let task = MathTask(5, 7);
let handle = task.start(); // Provided by the Thread trait

assert_eq!(handle.join().unwrap(), 12);
Source

fn start_with_builder(self, builder: Builder) -> JoinHandle<Self::Output>

Spawns a new thread using a custom std::thread::Builder to execute the run method.

This allows you to configure thread properties such as name, stack size, or other platform-specific options before spawning.

§Arguments
§Returns

Returns a std::thread::JoinHandle that can be used to wait for the thread to finish and extract its Output.

§Examples
use std::thread::Builder;
use struct_threads::{Runnable, Thread};

struct MathTask(i32, i32);

impl Runnable for MathTask {
    type Output = i32;
    fn run(self) -> Self::Output {
        self.0 + self.1
    }
}

let task = MathTask(5, 7);
let builder = Builder::new()
    .name("math-thread".to_string())
    .stack_size(4 * 1024 * 1024); // 4 MB stack

let handle = task.start_with_builder(builder);
assert_eq!(handle.join().unwrap(), 12);

Implementors§

Source§

impl<T: Runnable> Thread for T