Struct rendezvous_swap::RendezvousData
source · #[non_exhaustive]pub struct RendezvousData<T: Send + Sync> { /* private fields */ }
Expand description
Synchronise execution and swap data between threads.
Example: Swap thread data
use std::thread;
use rendezvous_swap::RendezvousData;
let (mut my_rendezvous, mut their_rendezvous) = RendezvousData::new(0, 0);
let handle = thread::spawn(move || {
let borrow = their_rendezvous.swap();
*borrow = 3;
let borrow = their_rendezvous.swap();
assert_eq!(7, *borrow);
});
let borrow = my_rendezvous.swap();
*borrow = 7;
let borrowed_data = my_rendezvous.swap();
assert_eq!(3, *borrowed_data);
Example: Safety
The following won’t compile due to the limited lifetime of the references provided by RendezvousData::swap
, you will get the familiar lifetime errors as if you are borrowing a struct element. This crate is safe because it is not possible for both threads to have mutable references to the same memory location at the same time.
ⓘ
use std::thread;
use rendezvous_swap::RendezvousData;
let (mut my_rendezvous, mut their_rendezvous) = RendezvousData::new(0, 0);
let handle = thread::spawn(move || {
their_rendezvous.swap(); // swap return values can be ignored
their_rendezvous.swap();
});
let old_borrow = my_rendezvous.swap(); // first mutable borrow occurs here
let new_borrow = my_rendezvous.swap(); // second mutable borrow occurs here
*old_borrow = 3; // first borrow is later used here
Implementations§
source§impl<T: Send + Sync> RendezvousData<T>
impl<T: Send + Sync> RendezvousData<T>
sourcepub fn new(data1: T, data2: T) -> (Self, Self)
pub fn new(data1: T, data2: T) -> (Self, Self)
Create a linked pair of RendezvousData
Arguments are the initial values for the data that will be swapped.
sourcepub fn swap<'lock>(&'lock mut self) -> &'lock mut T
pub fn swap<'lock>(&'lock mut self) -> &'lock mut T
Swap data with other thread and get a mutable reference to the data.
sourcepub fn swap_inline<'lock>(&'lock mut self) -> &'lock mut T
pub fn swap_inline<'lock>(&'lock mut self) -> &'lock mut T
Always inlined version of RendezvousData::swap