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