Module alloc::arcStable
[-]
[+]
[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 tasks:
use std::sync::Arc; use std::thread::Thread; let five = Arc::new(5i); for i in range(0u, 10) { let five = five.clone(); Thread::spawn(move || { println!("{}", five); }).detach(); }
Sharing mutable data safely between tasks with a Mutex
:
use std::sync::{Arc, Mutex}; use std::thread::Thread; let five = Arc::new(Mutex::new(5i)); for _ in range(0u, 10) { let five = five.clone(); Thread::spawn(move || { let mut number = five.lock().unwrap(); *number += 1; println!("{}", *number); // prints 6 }).detach(); }
Structs
Arc | An atomically reference counted wrapper for shared state. |
Weak | A weak pointer to an |
Functions
strong_count | Get the number of strong references to this value. |
weak_count | Get the number of weak references to this value. |