Bitpath

Boss lesson · Unit 04

Fearless concurrency

Threads that the borrow checker keeps honest

13 exercisesabout 3 min

What you practise

  • Threads and move closures, Send and Sync, 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?

Rust
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?

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.

Rust
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.

Rust
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.

One email when Bitpath is ready to try. Nothing else. Privacy