]>
Commit | Line | Data |
---|---|---|
3dfed10e XL |
1 | # Arc |
2 | ||
3 | When 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 |
6 | use std::sync::Arc; |
7 | use std::thread; | |
8 | ||
c295e0f8 XL |
9 | fn 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 | ``` |