Struct std::sync::Arc1.0.0 [] [src]

pub struct Arc<T> where T: ?Sized {
    // some fields omitted
}

An atomically reference counted wrapper for shared state. Destruction is deterministic, and will occur as soon as the last owner is gone. It is marked as Send because it uses atomic reference counting.

If you do not need thread-safety, and just need shared ownership, consider the Rc<T> type. It is the same as Arc<T>, but does not use atomics, making it both thread-unsafe as well as significantly faster when updating the reference count.

Examples

In this example, a large vector of data will be shared by several threads. First we wrap it with a Arc::new and then clone the Arc<T> reference for every thread (which will increase the reference count atomically).

use std::sync::Arc; use std::thread; fn main() { let numbers: Vec<_> = (0..100).collect(); let shared_numbers = Arc::new(numbers); for _ in 0..10 { // prepare a copy of reference here and it will be moved to the thread let child_numbers = shared_numbers.clone(); thread::spawn(move || { let local_numbers = &child_numbers[..]; // Work with the local numbers }); } }
use std::sync::Arc;
use std::thread;

fn main() {
    let numbers: Vec<_> = (0..100).collect();
    let shared_numbers = Arc::new(numbers);

    for _ in 0..10 {
        // prepare a copy of reference here and it will be moved to the thread
        let child_numbers = shared_numbers.clone();

        thread::spawn(move || {
            let local_numbers = &child_numbers[..];

            // Work with the local numbers
        });
    }
}

You can also share mutable data between threads safely by putting it inside Mutex and then share Mutex immutably with Arc<T> as shown below.

fn main() { use std::sync::{Arc, Mutex}; use std::thread; let five = Arc::new(Mutex::new(5)); for _ in 0..10 { let five = five.clone(); thread::spawn(move || { let mut number = five.lock().unwrap(); *number += 1; println!("{}", *number); // prints 6 }); } }
use std::sync::{Arc, Mutex};
use std::thread;

let five = Arc::new(Mutex::new(5));

for _ in 0..10 {
    let five = five.clone();

    thread::spawn(move || {
        let mut number = five.lock().unwrap();

        *number += 1;

        println!("{}", *number); // prints 6
    });
}

Methods

impl<T> Arc<T>

fn new(data: T) -> Arc<T>

Constructs a new Arc<T>.

Examples

fn main() { use std::sync::Arc; let five = Arc::new(5); }
use std::sync::Arc;

let five = Arc::new(5);

fn try_unwrap(this: Arc<T>) -> Result<T, Arc<T>>
1.4.0

Unwraps the contained value if the Arc<T> has exactly one strong reference.

Otherwise, an Err is returned with the same Arc<T>.

This will succeed even if there are outstanding weak references.

Examples

fn main() { 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))); }
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>
1.4.0

Downgrades the Arc<T> to a Weak<T> reference.

Examples

fn main() { use std::sync::Arc; let five = Arc::new(5); let weak_five = Arc::downgrade(&five); }
use std::sync::Arc;

let five = Arc::new(5);

let weak_five = Arc::downgrade(&five);

fn weak_count(this: &Arc<T>) -> usize

Unstable (arc_counts #28356)

: not clearly useful, and racy

Get the number of weak references to this value.

fn strong_count(this: &Arc<T>) -> usize

Unstable (arc_counts #28356)

: 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
1.4.0

Make a mutable reference into the given Arc<T>. If the Arc<T> has more than one strong reference, or any weak references, the inner data is cloned.

This is also referred to as a copy-on-write.

Examples

fn main() { 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); }
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>
1.4.0

Returns a mutable reference to the contained value if the Arc<T> has one strong reference and no weak references.

Examples

fn main() { 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()); }
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());

Trait Implementations

impl<T> Send for Arc<T> where T: Send + Sync + ?Sized

impl<T> Sync for Arc<T> where T: Send + Sync + ?Sized

impl<T, U> CoerceUnsized<Arc<U>> for Arc<T> where T: Unsize<U> + ?Sized, U: ?Sized

impl<T> Clone for Arc<T> where T: ?Sized

fn clone(&self) -> Arc<T>

Makes a clone of the Arc<T>.

This increases the strong reference count.

Examples

fn main() { use std::sync::Arc; let five = Arc::new(5); five.clone(); }
use std::sync::Arc;

let five = Arc::new(5);

five.clone();

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

impl<T> Deref for Arc<T> where T: ?Sized

type Target = T

The resulting type after dereferencing

fn deref(&self) -> &T

The method called to dereference a value

impl<T> Drop for Arc<T> where T: ?Sized

fn drop(&mut self)

Drops the Arc<T>.

This will decrement the strong reference count. If the strong reference count becomes zero and the only other references are Weak<T> ones, drops the inner value.

Examples

fn main() { use std::sync::Arc; { let five = Arc::new(5); // stuff drop(five); // explicit drop } { let five = Arc::new(5); // stuff } // implicit drop }
use std::sync::Arc;

{
    let five = Arc::new(5);

    // stuff

    drop(five); // explicit drop
}
{
    let five = Arc::new(5);

    // stuff

} // implicit drop

impl<T> PartialEq<Arc<T>> for Arc<T> where T: PartialEq<T> + ?Sized

fn eq(&self, other: &Arc<T>) -> bool

Equality for two Arc<T>s.

Two Arc<T>s are equal if their inner value are equal.

Examples

fn main() { use std::sync::Arc; let five = Arc::new(5); five == Arc::new(5); }
use std::sync::Arc;

let five = Arc::new(5);

five == Arc::new(5);

fn ne(&self, other: &Arc<T>) -> bool

Inequality for two Arc<T>s.

Two Arc<T>s are unequal if their inner value are unequal.

Examples

fn main() { use std::sync::Arc; let five = Arc::new(5); five != Arc::new(5); }
use std::sync::Arc;

let five = Arc::new(5);

five != Arc::new(5);

impl<T> PartialOrd<Arc<T>> for Arc<T> where T: PartialOrd<T> + ?Sized

fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering>

Partial comparison for two Arc<T>s.

The two are compared by calling partial_cmp() on their inner values.

Examples

fn main() { use std::sync::Arc; let five = Arc::new(5); five.partial_cmp(&Arc::new(5)); }
use std::sync::Arc;

let five = Arc::new(5);

five.partial_cmp(&Arc::new(5));

fn lt(&self, other: &Arc<T>) -> bool

Less-than comparison for two Arc<T>s.

The two are compared by calling < on their inner values.

Examples

fn main() { use std::sync::Arc; let five = Arc::new(5); five < Arc::new(5); }
use std::sync::Arc;

let five = Arc::new(5);

five < Arc::new(5);

fn le(&self, other: &Arc<T>) -> bool

'Less-than or equal to' comparison for two Arc<T>s.

The two are compared by calling <= on their inner values.

Examples

fn main() { use std::sync::Arc; let five = Arc::new(5); five <= Arc::new(5); }
use std::sync::Arc;

let five = Arc::new(5);

five <= Arc::new(5);

fn gt(&self, other: &Arc<T>) -> bool

Greater-than comparison for two Arc<T>s.

The two are compared by calling > on their inner values.

Examples

fn main() { use std::sync::Arc; let five = Arc::new(5); five > Arc::new(5); }
use std::sync::Arc;

let five = Arc::new(5);

five > Arc::new(5);

fn ge(&self, other: &Arc<T>) -> bool

'Greater-than or equal to' comparison for two Arc<T>s.

The two are compared by calling >= on their inner values.

Examples

fn main() { use std::sync::Arc; let five = Arc::new(5); five >= Arc::new(5); }
use std::sync::Arc;

let five = Arc::new(5);

five >= Arc::new(5);

impl<T> Ord for Arc<T> where T: Ord + ?Sized

fn cmp(&self, other: &Arc<T>) -> Ordering

This method returns an Ordering between self and other. Read more

impl<T> Eq for Arc<T> where T: Eq + ?Sized

impl<T> Display for Arc<T> where T: Display + ?Sized

fn fmt(&self, f: &mut Formatter) -> Result<()Error>

Formats the value using the given formatter.

impl<T> Debug for Arc<T> where T: Debug + ?Sized

fn fmt(&self, f: &mut Formatter) -> Result<()Error>

Formats the value using the given formatter.

impl<T> Pointer for Arc<T> where T: ?Sized

fn fmt(&self, f: &mut Formatter) -> Result<()Error>

Formats the value using the given formatter.

impl<T> Default for Arc<T> where T: Default

fn default() -> Arc<T>

Returns the "default value" for a type. Read more

impl<T> Hash for Arc<T> where T: Hash + ?Sized

fn hash<H>(&self, state: &mut H) where H: Hasher

Feeds this value into the state given, updating the hasher as necessary.

fn hash_slice<H>(data: &[Self], state: &mut H) where H: Hasher
1.3.0

Feeds a slice of this type into the state provided.

impl<T> From<T> for Arc<T>
1.6.0

fn from(t: T) -> Arc<T>

Performs the conversion.

impl<T> Borrow<T> for Arc<T> where T: ?Sized

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more

impl<T> AsRef<T> for Arc<T> where T: ?Sized
1.5.0

fn as_ref(&self) -> &T

Performs the conversion.

impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Arc<T>
1.9.0
[src]