Debian Codegraph @

third_party/rust/threadbound/README.md

raw
1 ThreadBound\<T\>
2 ================
3
4 [<img alt="github" src="https://img.shields.io/badge/github-dtolnay/threadbound-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/dtolnay/threadbound)
5 [<img alt="crates.io" src="https://img.shields.io/crates/v/threadbound.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/threadbound)
6 [<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-threadbound-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs" height="20">](https://docs.rs/threadbound)
7 [<img alt="build status" src="https://img.shields.io/github/actions/workflow/status/dtolnay/threadbound/ci.yml?branch=master&style=for-the-badge" height="20">](https://github.com/dtolnay/threadbound/actions?query=branch%3Amaster)
8
9 ThreadBound is a wrapper that binds a value to its original thread. The wrapper
10 gets to be [`Sync`] and [`Send`] but only the original thread on which the
11 ThreadBound was constructed can retrieve the underlying value.
12
13 [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html
14 [`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html
15
16 ```toml
17 [dependencies]
18 threadbound = "0.1"
19 ```
20
21 *Version requirement: rustc 1.31+*
22
23 <br>
24
25 ### Example
26
27 ```rust
28 extern crate threadbound;
29
30 use std::marker::PhantomData;
31 use std::rc::Rc;
32 use std::sync::Arc;
33 use threadbound::ThreadBound;
34
35 // Neither Send nor Sync. Maybe the index points into a
36 // thread-local interner.
37 #[derive(Copy, Clone)]
38 struct Span {
39 index: u32,
40 marker: PhantomData<Rc<()>>,
41 }
42
43 // Error types are always supposed to be Send and Sync.
44 // We can use ThreadBound to make it so.
45 struct Error {
46 span: ThreadBound<Span>,
47 message: String,
48 }
49
50 fn main() {
51 let err = Error {
52 span: ThreadBound::new(Span {
53 index: 99,
54 marker: PhantomData,
55 }),
56 message: "fearless concurrency".to_owned(),
57 };
58
59 // Original thread can see the contents.
60 assert_eq!(err.span.get_ref().unwrap().index, 99);
61
62 let err = Arc::new(err);
63 let err2 = err.clone();
64 std::thread::spawn(move || {
65 // Other threads cannot get access. Maybe they use
66 // a default value or a different codepath.
67 assert!(err2.span.get_ref().is_none());
68 });
69
70 // Original thread can still see the contents.
71 assert_eq!(err.span.get_ref().unwrap().index, 99);
72 }
73 ```
74
75 <br>
76
77 #### License
78
79 <sup>
80 Licensed under either of <a href="LICENSE-APACHE">Apache License, Version
81 2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option.
82 </sup>
83
84 <br>
85
86 <sub>
87 Unless you explicitly state otherwise, any contribution intentionally submitted
88 for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
89 be dual licensed as above, without any additional terms or conditions.
90 </sub>