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

Structs

Arc

An atomically reference counted wrapper for shared state.

Weak

A weak pointer to an Arc.