Skip to main content

Module shared_vec

Module shared_vec 

Source
Expand description

§Manually shared vector

SharedVec is the Vec-based counterpart to SharedBox. It owns the original allocation and lets you create multiple immutable SharedVecRef values that can be sent to other threads while keeping a single shared owner.

The API is similar to SharedBox:

  • use SharedVec::from_vec to create a shared vector from a Vec
  • use SharedVec::borrow to create a SharedVecRef
  • use SharedVec::try_return to give a borrowed reference back
  • use SharedVec::try_into_vec to recover the original Vec once no references remain
use std::thread;
use manual_share::SharedVec;

let values = vec![1, 2, 3];
let mut shared = SharedVec::from_vec(values);

let shared_ref = shared.borrow();
let handle = thread::spawn(move || {
    assert_eq!(shared_ref.as_slice(), &[1, 2, 3]);
    shared_ref
});

let shared_ref = shared.borrow();
let handle2 = thread::spawn(move || {
    assert_eq!(shared_ref.as_slice(), &[1, 2, 3]);
    shared_ref
});

shared.try_return(handle.join().unwrap()).unwrap();
shared.try_return(handle2.join().unwrap()).unwrap();

let values = shared.try_into_vec().unwrap();
assert_eq!(values, vec![1, 2, 3]);

Structs§

SharedVec
A structure owning the original Vec which can be used to create multiple immutable SharedVecRef values to send to other threads. It uses a counter to record how many references have been created and not returned yet.
SharedVecMut
A container of a Vec allocation that can be split into multiple SharedVecPart values.
SharedVecPart
A slice-like view into a segment of a SharedVecMut allocation.
SharedVecRef
A reference to SharedVec that can be sent to other threads.