You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-06-15 13:50:27 +02:00
Publish Comprehensive Rust 🦀
This commit is contained in:
25
src/concurrency/shared_state/arc.md
Normal file
25
src/concurrency/shared_state/arc.md
Normal file
@ -0,0 +1,25 @@
|
||||
# `Arc`
|
||||
|
||||
[`Arc<T>`][1] allows shared read-only access via its `clone` method:
|
||||
|
||||
```rust,editable
|
||||
use std::thread;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn main() {
|
||||
let v = Arc::new(vec![10, 20, 30]);
|
||||
let mut handles = Vec::new();
|
||||
for _ in 1..5 {
|
||||
let v = v.clone();
|
||||
handles.push(thread::spawn(move || {
|
||||
let thread_id = thread::current().id();
|
||||
println!("{thread_id:?}: {v:?}");
|
||||
}));
|
||||
}
|
||||
|
||||
handles.into_iter().for_each(|h| h.join().unwrap());
|
||||
println!("v: {v:?}");
|
||||
}
|
||||
```
|
||||
|
||||
[1]: https://doc.rust-lang.org/std/sync/struct.Arc.html
|
19
src/concurrency/shared_state/example.md
Normal file
19
src/concurrency/shared_state/example.md
Normal file
@ -0,0 +1,19 @@
|
||||
# Example
|
||||
|
||||
Let us see `Arc` and `Mutex` in action:
|
||||
|
||||
```rust,editable,compile_fail
|
||||
use std::thread;
|
||||
// use std::sync::{Arc, Mutex};
|
||||
|
||||
fn main() {
|
||||
let mut v = vec![10, 20, 30];
|
||||
let handle = thread::spawn(|| {
|
||||
v.push(10);
|
||||
});
|
||||
v.push(1000);
|
||||
|
||||
handle.join().unwrap();
|
||||
println!("v: {v:?}");
|
||||
}
|
||||
```
|
28
src/concurrency/shared_state/mutex.md
Normal file
28
src/concurrency/shared_state/mutex.md
Normal file
@ -0,0 +1,28 @@
|
||||
# `Mutex`
|
||||
|
||||
[`Mutex<T>`][1] ensures mutual exclusion _and_ allows mutable access to `T`
|
||||
behind a read-only interface:
|
||||
|
||||
```rust,editable
|
||||
use std::sync::Mutex;
|
||||
|
||||
fn main() {
|
||||
let v: Mutex<Vec<i32>> = Mutex::new(vec![10, 20, 30]);
|
||||
println!("v: {:?}", v.lock().unwrap());
|
||||
|
||||
{
|
||||
let v: &Mutex<Vec<i32>> = &v;
|
||||
let mut guard = v.lock().unwrap();
|
||||
guard.push(40);
|
||||
}
|
||||
|
||||
println!("v: {:?}", v.lock().unwrap());
|
||||
}
|
||||
```
|
||||
|
||||
Notice how we have a [`impl<T: Send> Sync for Mutex<T>`][2] blanket
|
||||
implementation.
|
||||
|
||||
[1]: https://doc.rust-lang.org/std/sync/struct.Mutex.html
|
||||
[2]: https://doc.rust-lang.org/std/sync/struct.Mutex.html#impl-Sync-for-Mutex%3CT%3E
|
||||
[3]: https://doc.rust-lang.org/std/sync/struct.Arc.html
|
Reference in New Issue
Block a user