Boss lesson · Unit 04
Fearless concurrency
Threads that the borrow checker keeps honest
What you practise
- Threads and
moveclosures,SendandSync, channels,Arc<Mutex<T>> - The data race that will not compile
- Modules and Cargo in outline
Try a question from this lesson
Pick one
thread::spawn runs a closure on a new thread, which may outlive the function that started it. Which line does the compiler reject?
use std::thread;
let v = vec![1, 2, 3];
let h = thread::spawn(|| {
println!("{}", v.len());
});
h.join().unwrap();Hint
The closure only borrows v. What if the thread is still running when v is dropped?
Correct answer
Line 3
Why
The closure borrows v, and a spawned thread has no fixed end: "closure may outlive the current function, but it borrows v". The error is on the closure, and the compiler's help names the fix.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
spawn, move and join
thread::spawn starts an OS thread and returns a handle. handle.join() waits for the thread to finish.
move before a closure makes it take ownership of every variable it uses. The data then belongs to the new thread and no reference can dangle. Rust threads run truly in parallel, with no global lock like Python's.
use std::thread;
let name = String::from("worker");
let h = thread::spawn(move || {
println!("hi from {name}");
});
h.join().unwrap();
println!("done");Concept
Arc and Mutex
To let several threads change one value, wrap it twice.
Mutex<T> lets one thread in at a time. lock() waits for its turn and returns a guard, which unlocks when it is dropped. The data can only be reached through the guard, so forgetting to lock is impossible.
Arc<T> is Rc with a thread-safe counter, so every thread can own the mutex.
use std::sync::{Arc, Mutex};
let m = Arc::new(Mutex::new(5));
let m2 = Arc::clone(&m);
*m2.lock().unwrap() += 1;
println!("{}", m.lock().unwrap());Concept
Send and Sync
Two marker traits carry this knowledge. A type is Send if a value of it may move to another thread, and Sync if references to it may be shared between threads.
The compiler works both out from a type's fields. Rc is neither, and RefCell is not Sync. thread::spawn demands Send, so thread-unsafe types are stopped at compile time.
9 more exercises in the app
- 1× fill the blanks
- 4× type the answer
- 2× multiple choice
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.