Skip to content

Commit e9c7452

Browse files
committed
concurrency: also show shared ownership when combining Arc/Mutex
1 parent fbb81fe commit e9c7452

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed

src/concurrency/shared-state/example.md

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,15 @@ use std::thread;
1212
1313
fn main() {
1414
let v = vec![10, 20, 30];
15-
let handle = thread::spawn(|| {
16-
v.push(10);
17-
});
18-
v.push(1000);
15+
let mut handles = Vec::new();
16+
for i in 0..5 {
17+
handles.push(thread::spawn(|| {
18+
v.push(10 * i);
19+
println!("v: {v:?}");
20+
}));
21+
}
1922
20-
handle.join().unwrap();
21-
println!("v: {v:?}");
23+
handles.into_iter().for_each(|h| h.join().unwrap());
2224
}
2325
```
2426

@@ -33,20 +35,17 @@ use std::thread;
3335
fn main() {
3436
let v = Arc::new(Mutex::new(vec![10, 20, 30]));
3537
36-
let v2 = Arc::clone(&v);
37-
let handle = thread::spawn(move || {
38-
let mut v2 = v2.lock().unwrap();
39-
v2.push(10);
40-
});
41-
42-
{
43-
let mut v = v.lock().unwrap();
44-
v.push(1000);
38+
for i in 0..5 {
39+
let v = Arc::clone(&v);
40+
let mut handles = Vec::new();
41+
handles.push(thread::spawn(move || {
42+
let mut v = v.lock().unwrap();
43+
v.push(10 * i);
44+
println!("v: {v:?}");
45+
}));
4546
}
4647
47-
handle.join().unwrap();
48-
49-
println!("v: {v:?}");
48+
handles.into_iter().for_each(|h| h.join().unwrap());
5049
}
5150
```
5251

@@ -56,7 +55,7 @@ Notable parts:
5655
orthogonal.
5756
- Wrapping a `Mutex` in an `Arc` is a common pattern to share mutable state
5857
between threads.
59-
- `v: Arc<_>` needs to be cloned as `v2` before it can be moved into another
58+
- `v: Arc<_>` needs to be cloned to make a new reference for each new spawned
6059
thread. Note `move` was added to the lambda signature.
6160
- Blocks are introduced to narrow the scope of the `LockGuard` as much as
6261
possible.

0 commit comments

Comments
 (0)