]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/std/arc.md
New upstream version 1.63.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / std / arc.md
CommitLineData
3dfed10e
XL
1# Arc
2
923072b8
FG
3When shared ownership between threads is needed, `Arc`(Atomically Reference
4Counted) can be used. This struct, via the `Clone` implementation can create
5a reference pointer for the location of a value in the memory heap while
6increasing the reference counter. As it shares ownership between threads, when
7the last reference pointer to a value is out of scope, the variable is dropped.
3dfed10e
XL
8
9```rust,editable
923072b8 10use std::time::Duration;
3dfed10e
XL
11use std::sync::Arc;
12use std::thread;
13
c295e0f8
XL
14fn main() {
15 // This variable declaration is where its value is specified.
16 let apple = Arc::new("the same apple");
3dfed10e 17
c295e0f8 18 for _ in 0..10 {
923072b8
FG
19 // Here there is no value specification as it is a pointer to a
20 // reference in the memory heap.
c295e0f8 21 let apple = Arc::clone(&apple);
3dfed10e 22
c295e0f8
XL
23 thread::spawn(move || {
24 // As Arc was used, threads can be spawned using the value allocated
25 // in the Arc variable pointer's location.
26 println!("{:?}", apple);
27 });
28 }
3dfed10e 29
923072b8
FG
30 // Make sure all Arc instances are printed from spawned threads.
31 thread::sleep(Duration::from_secs(1));
32}
3dfed10e 33```