#send-sync #send #worker-thread #sync #type #values #different

diplomatic-bag

A wrapper type that allows you to send !Send types to different threads

5 unstable releases

0.3.1 May 17, 2022
0.3.0 May 17, 2022
0.2.0 Jun 27, 2021
0.1.1 Feb 13, 2021
0.1.0 Feb 13, 2021

#550 in Concurrency

Download history 9/week @ 2024-06-10 17/week @ 2024-07-01 108/week @ 2024-07-15 11/week @ 2024-07-22 77/week @ 2024-07-29 44/week @ 2024-08-12 25/week @ 2024-08-26 61/week @ 2024-09-23

63 downloads per month

MIT/Apache

34KB
360 lines

Diplomatic Bag

Crates.io API reference License Rust

Hide !Send and !Sync types inside a DiplomaticBag which can be sent between thread freely.

let one = DiplomaticBag::new(|| Rc::new(RefCell::new(1)));
let two = DiplomaticBag::new(|| Rc::new(RefCell::new(2)));
let three: u8 = std::thread::spawn(|| {
    one.as_ref()
        .zip(two.as_ref())
        .map(|(one, two)| *one.borrow() + *two.borrow())
        .into_inner()
}).join()?;

(I don't know why you'd want to do this ^, but I promise this comes in handy for !Send types not in std, for example, cpal's Stream type.)

How it works

All the operations on values inside DiplomaticBags are sent to a worker thread (the home country 😉). This means the values are only ever read on one thread, allowing the DiplomaticBag to be Send even if the type it contains is not. This model does have some drawbacks, see the docs for more information.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~395KB