Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 56 additions & 1 deletion 1_concepts/1_8_thread_safety/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,58 @@
#![allow(warnings)]

use std::{
cell::Cell,
marker::PhantomData,
rc::Rc,
sync::{Arc, Mutex, MutexGuard},
thread,
};

fn main() {
println!("Implement me!");
let only_send = OnlySend(Cell::new(0));
let sync_and_send = SyncAndSend(0);
let not_sync_not_send = NotSyncNotSend(Rc::new(0));
let only_sync = Arc::new(Mutex::new(SyncAndSend(0)));

let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&only_sync);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();

num.0 += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}

println!("{:?}", only_sync);
println!("{:?}", only_send);
println!("{:?}", sync_and_send);

let only_sync_instance = OnlySync(SyncAndSend(0), PhantomData);
println!("{:?}", only_sync_instance);

let handle = thread::spawn(move || {
println!("{:?}", only_send);
println!("{:?}", sync_and_send);
});

handle.join().unwrap();
}

#[derive(Debug)]
struct OnlySync<T: Sync>(T, PhantomData<Rc<()>>);

#[derive(Debug)]
struct OnlySend<T: Copy>(Cell<T>);

#[derive(Debug)]
struct SyncAndSend(i32);

#[derive(Debug)]
struct NotSyncNotSend<T>(Rc<T>);

unsafe impl<T: Sync> Sync for OnlySync<T> {}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ Each step must be performed as a separate [PR (pull request)][PR] with an approp
- [ ] [1.5. Conversions, casting and dereferencing][Step 1.5] (1 day)
- [ ] [1.6. Static and dynamic dispatch][Step 1.6] (1 day)
- [ ] [1.7. `Sized` and `?Sized` types][Step 1.7] (1 day)
- [ ] [1.8. Thread safety][Step 1.8] (1 day)
- [x] [1.8. Thread safety][Step 1.8] (1 day)
- [ ] [1.9. Phantom types][Step 1.9] (1 day)
- [ ] [2. Idioms][Step 2] (2 days, after all sub-steps)
- [ ] [2.1. Rich types ensure correctness][Step 2.1] (1 day)
Expand Down