Skip to content

Commit fbb81fe

Browse files
committed
concurrency: demonstrate dynamic ownership with Arc
Ownership is the responsibility to free a value. Previously, `v` was always freed by the main thread because it kept the original `Arc` instance. It was difficult to explain why this example did not simply use scoped threads instead. Now we see that multi-threaded dynamic ownership with `Arc` results in a dynamic decision of which thread will clean up a given value.
1 parent d0d8168 commit fbb81fe

File tree

1 file changed

+20
-3
lines changed
  • src/concurrency/shared-state

1 file changed

+20
-3
lines changed

src/concurrency/shared-state/arc.md

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,42 @@ minutes: 5
44

55
# `Arc`
66

7-
[`Arc<T>`][1] allows shared read-only access via `Arc::clone`:
7+
[`Arc<T>`][1] allows shared, read-only ownership via `Arc::clone`:
88

99
```rust,editable
10+
use rand::Rng;
1011
use std::sync::Arc;
1112
use std::thread;
1213
14+
/// A struct that prints which thread drops it.
15+
#[derive(Debug)]
16+
struct WhereDropped(Vec<i32>);
17+
18+
impl Drop for WhereDropped {
19+
fn drop(&mut self) {
20+
println!("Dropped by {:?}", thread::current().id())
21+
}
22+
}
23+
1324
fn main() {
14-
let v = Arc::new(vec![10, 20, 30]);
25+
let v = Arc::new(WhereDropped(vec![10, 20, 30]));
1526
let mut handles = Vec::new();
1627
for _ in 0..5 {
1728
let v = Arc::clone(&v);
1829
handles.push(thread::spawn(move || {
30+
// Randomly sleep for 0-500ms.
31+
let ms = rand::rng().random_range(0..500);
32+
std::thread::sleep(std::time::Duration::from_millis(ms));
1933
let thread_id = thread::current().id();
2034
println!("{thread_id:?}: {v:?}");
2135
}));
2236
}
2337
38+
// Now only the spawned threads will hold clones of `v`.
39+
drop(v);
40+
41+
// When the last spawned thread finishes, it will drop `v`'s contents.
2442
handles.into_iter().for_each(|h| h.join().unwrap());
25-
println!("v: {v:?}");
2643
}
2744
```
2845

0 commit comments

Comments
 (0)