#sync #thread #send-sync #original #value #wrapper #phantom-data

threadbound

Make any value Sync but only available on its original thread

8 releases

0.1.7 Jul 15, 2023
0.1.6 Mar 3, 2023
0.1.5 Dec 17, 2022
0.1.4 Aug 3, 2022
0.1.0 Nov 17, 2018

#120 in Concurrency

Download history 469/week @ 2024-06-14 198/week @ 2024-06-21 446/week @ 2024-06-28 582/week @ 2024-07-05 755/week @ 2024-07-12 443/week @ 2024-07-19 697/week @ 2024-07-26 495/week @ 2024-08-02 403/week @ 2024-08-09 334/week @ 2024-08-16 479/week @ 2024-08-23 276/week @ 2024-08-30 417/week @ 2024-09-06 710/week @ 2024-09-13 353/week @ 2024-09-20 293/week @ 2024-09-27

1,821 downloads per month

MIT/Apache

10KB
52 lines

ThreadBound<T>

github crates.io docs.rs build status

ThreadBound 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 ThreadBound was constructed can retrieve the underlying value.

[dependencies]
threadbound = "0.1"

Version requirement: rustc 1.31+


Example

extern crate threadbound;

use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::Arc;
use threadbound::ThreadBound;

// 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 ThreadBound to make it so.
struct Error {
    span: ThreadBound<Span>,
    message: String,
}

fn main() {
    let err = Error {
        span: ThreadBound::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);
}

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

No runtime deps