@@ -12,13 +12,15 @@ use std::thread;
12
12
13
13
fn main() {
14
14
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
+ }
19
22
20
- handle.join().unwrap();
21
- println!("v: {v:?}");
23
+ handles.into_iter().for_each(|h| h.join().unwrap());
22
24
}
23
25
```
24
26
@@ -33,20 +35,17 @@ use std::thread;
33
35
fn main() {
34
36
let v = Arc::new(Mutex::new(vec![10, 20, 30]));
35
37
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
+ }));
45
46
}
46
47
47
- handle.join().unwrap();
48
-
49
- println!("v: {v:?}");
48
+ handles.into_iter().for_each(|h| h.join().unwrap());
50
49
}
51
50
```
52
51
@@ -56,7 +55,7 @@ Notable parts:
56
55
orthogonal.
57
56
- Wrapping a ` Mutex ` in an ` Arc ` is a common pattern to share mutable state
58
57
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
60
59
thread. Note ` move ` was added to the lambda signature.
61
60
- Blocks are introduced to narrow the scope of the ` LockGuard ` as much as
62
61
possible.
0 commit comments