Crate threadalone

Source
Expand description

This is a fork of dtolnay’s threadbound crate, which allows implementing Send on non-Copy types.

The reason that the original crate does not allow it is, if a ThreadBound object dropped on another thread from where it was created, it cannot be handled in any way. Instead, this crate aborts if that happens: so be very cautious when using this crate on multi-threaded environemnt.


githubcrates-iodocs-rs


ThreadAlone<T> is a wrapper that binds a value to its original thread. The wrapper gets to be Sync and Send but only the original thread on which the ThreadAlone was constructed can retrieve the underlying value.

§Example

use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::Arc;
use threadalone::ThreadAlone;

// Neither Send nor Sync. Maybe the index points into a
// thread-local interner.
#[derive(Copy, Clone)]
struct Span {
    index: u32,
    marker: PhantomData<Rc<()>>,
}

// Error types are always supposed to be Send and Sync.
// We can use ThreadAlone to make it so.
struct Error {
    span: ThreadAlone<Span>,
    message: String,
}

let err = Error {
    span: ThreadAlone::new(Span {
        index: 99,
        marker: PhantomData,
    }),
    message: "fearless concurrency".to_owned(),
};

// Original thread can see the contents.
assert_eq!(err.span.get_ref().unwrap().index, 99);

let err = Arc::new(err);
let err2 = err.clone();
std::thread::spawn(move || {
    // Other threads cannot get access. Maybe they use
    // a default value or a different codepath.
    assert!(err2.span.get_ref().is_none());
});

// Original thread can still see the contents.
assert_eq!(err.span.get_ref().unwrap().index, 99);

Structs§

ThreadAlone
ThreadAlone is a Sync-maker and Send-maker that allows accessing a value of type T only from the original thread on which the ThreadAlone was constructed.