[][src]Crate scoped_threads

Lightweight, safe and idiomatic scoped threads

This crate provides a scoped alternative to std::thread, ie threads that can use non-static data, such as references to the stack of the parent thread. It mimics std's thread interface, so there is nothing to learn to use this crate. There is a meaningful difference, though: a dropped JoinHandle joins the spawned thread instead of detaching it, to ensure that borrowed data is still valid. Additionnally, this crate does not redefine types and functions that are not related to threads being scoped, such as thread::park.

It is lightweight in the sense that it does not uses expensive thread synchronisation such as Arc, locks or channels. It does not even uses atomics !

This API beeing nearly the same as std's and this documentation having no intention to be a copy of std's documentation on threads, you'll find much more details in the latter.

Cargo features

This crate exposes a feature nightly, which uses unstable functions from std. It changes some facets of the crate's implementation to remove the two required memory allocations.

Example

Share a Mutex without Arc

use std::sync::Mutex;

// This struct is not static, so it cannot be send in standard threads
struct Counter<'a> {
    count: &'a Mutex<i32>,
    increment: i32,
}

let count = Mutex::new(0);

let counter = Counter {
    count: &count,
    increment: 2,
};

// Send the Counter in another thread
let join_handle = scoped_threads::spawn(move || {
    *counter.count.lock().unwrap() += counter.increment;
});

// Wait for the spawned thread to finish
join_handle.join();

assert_eq!(*count.lock().unwrap(), 2);

Structs

Builder

Thread factory, which can be used in order to configure the properties of a new thread.

JoinHandle

Enables to join on a spawned thread.

Functions

spawn

Spawns a new thread.