]>
Commit | Line | Data |
---|---|---|
3dfed10e XL |
1 | # Arc |
2 | ||
923072b8 FG |
3 | When shared ownership between threads is needed, `Arc`(Atomically Reference |
4 | Counted) can be used. This struct, via the `Clone` implementation can create | |
5 | a reference pointer for the location of a value in the memory heap while | |
6 | increasing the reference counter. As it shares ownership between threads, when | |
7 | the last reference pointer to a value is out of scope, the variable is dropped. | |
3dfed10e XL |
8 | |
9 | ```rust,editable | |
923072b8 | 10 | use std::time::Duration; |
3dfed10e XL |
11 | use std::sync::Arc; |
12 | use std::thread; | |
13 | ||
c295e0f8 XL |
14 | fn 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 | ``` |