1
0
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:
Martin Geisler
2022-12-21 16:36:30 +01:00
commit c212a473ba
252 changed files with 8047 additions and 0 deletions

View 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

View 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:?}");
}
```

View 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