Function collective::thread::handle::spawn

source ·
pub fn spawn<F, T>(notify_sender: Sender<Thread>, f: F) -> ThreadHandle<T>where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
Expand description

Like std::thread::spawn, but returns a ThreadHandle instead.

Examples

Create ten threads and wait for all threads to finish.

use collective::thread::handle::spawn;
use std::{
    collections::HashMap,
    sync::{mpsc, Arc, Barrier},
};

let (monitor_tx, monitor_rx) = mpsc::channel();
let barrier = Arc::new(Barrier::new(10));

let mut end_handles = HashMap::new();

for _ in 0..10 {
    let bc = barrier.clone();

    let handle = spawn(monitor_tx.clone(), move || {
        /// Sync all threads.
        bc.wait();
    });

    end_handles.insert(handle.thread().id(), handle.get_end_handle());
}

// Loop until we have been notified of every thread ending.
loop {
    let thread = monitor_rx.recv().unwrap();

    end_handles.remove(&thread.id());

    if end_handles.is_empty() {
        break;
    }
}