Bitpath

Lesson 2 · Unit 08

Sharing and threads

Box, Rc and RefCell in outline, then threads, locks and channels

13 exercisesabout 3 min

What you practise

  • Box, Rc and RefCell in outline, thread::spawn with move, Arc<Mutex<T>>, channels

Try a question from this lesson

Pick one

Two parts of a program both want to own one list. Which line does the compiler reject?

Rust
let list = vec![1, 2, 3];
let a = list;
let b = list;
println!("{}", a.len() + b.len());
Hint

A vector has one owner. Follow where the ownership of list goes, line by line.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Rc: one value, several owners

Rc::new(value) wraps a value so that it can have several owners.

Rc::clone(&a) does not copy the value. It makes one more owner of the same value and adds 1 to a count. When an owner goes away the count drops, and at zero the value is freed.

The name stands for reference counted.

Rust
use std::rc::Rc;
let a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
println!("{} {}", a.len(), b.len());
println!("{}", Rc::strong_count(&a));

Concept

A second line of work

A thread is a second line of work that runs at the same time as the first.

thread::spawn takes a closure and starts it on a new thread. move before the bars makes the closure the owner of everything it uses.

spawn hands back a handle. join() waits until that thread is finished.

Rust
use std::thread;
let name = String::from("worker");
let handle = thread::spawn(move || {
    println!("hello from {}", name);
});
handle.join().unwrap();
println!("main is done");

Concept

Arc and Mutex

An Rc may not cross into a thread: its count is not safe there. Arc is the Rc that is.

A Mutex guards a value so that one thread at a time can touch it. lock() waits for its turn and hands out a writing loan, and * reaches the value behind it.

Arc<Mutex<...>> is the pair for data that threads share and change.

Rust
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
let total = Arc::new(Mutex::new(0));
let mine = Arc::clone(&total);
let handle = thread::spawn(move || {
    *mine.lock().unwrap() += 5;
});
handle.join().unwrap();
println!("{}", total.lock().unwrap());

9 more exercises in the app

  • 3× type the answer
  • 3× multiple choice
  • 2× fill the blanks
  • 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