]>
Commit | Line | Data |
---|---|---|
1 | # Arc | |
2 | ||
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. | |
8 | ||
9 | ```rust,editable | |
10 | use std::time::Duration; | |
11 | use std::sync::Arc; | |
12 | use std::thread; | |
13 | ||
14 | fn main() { | |
15 | // This variable declaration is where its value is specified. | |
16 | let apple = Arc::new("the same apple"); | |
17 | ||
18 | for _ in 0..10 { | |
19 | // Here there is no value specification as it is a pointer to a | |
20 | // reference in the memory heap. | |
21 | let apple = Arc::clone(&apple); | |
22 | ||
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 | } | |
29 | ||
30 | // Make sure all Arc instances are printed from spawned threads. | |
31 | thread::sleep(Duration::from_secs(1)); | |
32 | } | |
33 | ``` |