Struct std::sync::Arc
[−]
[src]
pub struct Arc<T> where T: ?Sized {
_ptr: Shared<ArcInner<T>>,
}
An atomically reference counted wrapper for shared state.
Examples
In this example, a large vector is shared between several threads.
With simple pipes, without Arc
, a copy would have to be made for each
thread.
When you clone an Arc<T>
, it will create another pointer to the data and
increase the reference counter.
use std::sync::Arc; use std::thread; fn main() { let numbers: Vec<_> = (0..100u32).collect(); let shared_numbers = Arc::new(numbers); for _ in 0..10 { let child_numbers = shared_numbers.clone(); thread::spawn(move || { let local_numbers = &child_numbers[..]; // Work with the local numbers }); } }
Fields
_ptr |
Methods
impl<T> Arc<T>
fn new(data: T) -> Arc<T>
fn try_unwrap(this: Arc<T>) -> Result<T, Arc<T>>
Unwraps the contained value if the Arc<T>
has only one strong reference.
This will succeed even if there are outstanding weak references.
Otherwise, an Err
is returned with the same Arc<T>
.
Examples
use std::sync::Arc; let x = Arc::new(3); assert_eq!(Arc::try_unwrap(x), Ok(3)); let x = Arc::new(4); let _y = x.clone(); assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
impl<T> Arc<T> where T: ?Sized
fn downgrade(this: &Arc<T>) -> Weak<T>
Downgrades the Arc<T>
to a Weak<T>
reference.
Examples
use std::sync::Arc; let five = Arc::new(5); let weak_five = Arc::downgrade(&five);
fn weak_count(this: &Arc<T>) -> usize
arc_counts
): not clearly useful, and racy
Get the number of weak references to this value.
fn strong_count(this: &Arc<T>) -> usize
arc_counts
): not clearly useful, and racy
Get the number of strong references to this value.
impl<T> Arc<T> where T: Clone
fn make_mut(this: &mut Arc<T>) -> &mut T
Make a mutable reference into the given Arc<T>
by cloning the inner
data if the Arc<T>
doesn't have one strong reference and no weak
references.
This is also referred to as a copy-on-write.
Examples
use std::sync::Arc; let mut data = Arc::new(5); *Arc::make_mut(&mut data) += 1; // Won't clone anything let mut other_data = data.clone(); // Won't clone inner data *Arc::make_mut(&mut data) += 1; // Clones inner data *Arc::make_mut(&mut data) += 1; // Won't clone anything *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything // Note: data and other_data now point to different numbers assert_eq!(*data, 8); assert_eq!(*other_data, 12);
impl<T> Arc<T> where T: ?Sized
fn get_mut(this: &mut Arc<T>) -> Option<&mut T>
Returns a mutable reference to the contained value if the Arc<T>
has
one strong reference and no weak references.
Examples
use std::sync::Arc; let mut x = Arc::new(3); *Arc::get_mut(&mut x).unwrap() = 4; assert_eq!(*x, 4); let _y = x.clone(); assert!(Arc::get_mut(&mut x).is_none());