You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-07-04 13:50:28 +02:00
concurrency: also show shared ownership when combining Arc/Mutex
This commit is contained in:
@ -12,13 +12,15 @@ use std::thread;
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let v = vec![10, 20, 30];
|
let v = vec![10, 20, 30];
|
||||||
let handle = thread::spawn(|| {
|
let mut handles = Vec::new();
|
||||||
v.push(10);
|
for i in 0..5 {
|
||||||
});
|
handles.push(thread::spawn(|| {
|
||||||
v.push(1000);
|
v.push(10 * i);
|
||||||
|
println!("v: {v:?}");
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
handle.join().unwrap();
|
handles.into_iter().for_each(|h| h.join().unwrap());
|
||||||
println!("v: {v:?}");
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -32,21 +34,17 @@ use std::thread;
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let v = Arc::new(Mutex::new(vec![10, 20, 30]));
|
let v = Arc::new(Mutex::new(vec![10, 20, 30]));
|
||||||
|
let mut handles = Vec::new();
|
||||||
let v2 = Arc::clone(&v);
|
for i in 0..5 {
|
||||||
let handle = thread::spawn(move || {
|
let v = Arc::clone(&v);
|
||||||
let mut v2 = v2.lock().unwrap();
|
handles.push(thread::spawn(move || {
|
||||||
v2.push(10);
|
let mut v = v.lock().unwrap();
|
||||||
});
|
v.push(10 * i);
|
||||||
|
println!("v: {v:?}");
|
||||||
{
|
}));
|
||||||
let mut v = v.lock().unwrap();
|
|
||||||
v.push(1000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handle.join().unwrap();
|
handles.into_iter().for_each(|h| h.join().unwrap());
|
||||||
|
|
||||||
println!("v: {v:?}");
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -56,7 +54,7 @@ Notable parts:
|
|||||||
orthogonal.
|
orthogonal.
|
||||||
- Wrapping a `Mutex` in an `Arc` is a common pattern to share mutable state
|
- Wrapping a `Mutex` in an `Arc` is a common pattern to share mutable state
|
||||||
between threads.
|
between threads.
|
||||||
- `v: Arc<_>` needs to be cloned as `v2` before it can be moved into another
|
- `v: Arc<_>` needs to be cloned to make a new reference for each new spawned
|
||||||
thread. Note `move` was added to the lambda signature.
|
thread. Note `move` was added to the lambda signature.
|
||||||
- Blocks are introduced to narrow the scope of the `LockGuard` as much as
|
- Blocks are introduced to narrow the scope of the `LockGuard` as much as
|
||||||
possible.
|
possible.
|
||||||
|
Reference in New Issue
Block a user