Module alloc::arc [] [src]

Threadsafe reference-counted boxes (the Arc<T> type).

The Arc<T> type provides shared ownership of an immutable value. 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.

The downgrade method can be used to create a non-owning Weak<T> pointer to the box. A Weak<T> pointer can be upgraded to an Arc<T> pointer, but will return None if the value has already been dropped.

For example, a tree with parent pointers can be represented by putting the nodes behind strong Arc<T> pointers, and then storing the parent pointers as Weak<T> pointers.

Examples

Sharing some immutable data between threads:

use std::sync::Arc;
use std::thread;

let five = Arc::new(5);

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

    thread::spawn(move || {
        println!("{:?}", five);
    });
}

Sharing mutable data safely between threads with a Mutex:

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
    });
}

Reexports

use core::prelude::v1::*;
use boxed::Box;
use core::sync::atomic;
use core::sync::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst};
use core::borrow;
use core::fmt;
use core::cmp::Ordering;
use core::mem::{align_of_val, size_of_val};
use core::intrinsics::abort;
use core::mem;
use core::mem::uninitialized;
use core::ops::Deref;
use core::ops::CoerceUnsized;
use core::ptr::{self, Shared};
use core::marker::Unsize;
use core::hash::{Hash, Hasher};
use core::{usize, isize};
use core::convert::From;
use heap::deallocate;

Structs

Arc

An atomically reference counted wrapper for shared state.

ArcInner
Weak

A weak pointer to an Arc.

Constants

MAX_REFCOUNT