Practice 14

Concurrency

Read each program and pick an answer. Some programs do not compile, and that can be the right answer. Your choice is checked as soon as you pick it, and saved in this browser.Need a refresher? Read lesson 14.

Course

0 of 45 answered·0 correct

Threads and std::thread

1.

What does this print?

use std::thread;

fn main() {
    let handle = thread::spawn(|| 10 + 20);
    println!("{}", handle.join().unwrap());
}
2.

What does this print?

use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        println!("inside the thread");
        99
    });
    let result = handle.join().unwrap();
    println!("result: {result}");
}
3.

What does this print?

use std::thread;

fn main() {
    let handle = thread::spawn(|| String::from("done"));
    println!("{}", handle.join().unwrap());
}
4.

This program joins each thread before starting the next one. What does it print?

use std::thread;

fn main() {
    let a = thread::spawn(|| println!("first"));
    a.join().unwrap();
    let b = thread::spawn(|| println!("second"));
    b.join().unwrap();
}
5.

What does this print?

use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        let mut total = 0;
        for n in 1..=4 {
            total += n * n;
        }
        total
    });
    println!("{}", handle.join().unwrap());
}
6.

The spawned thread panics, but the panic does not crash main: join catches it and returns Err instead of Ok. What does the last line print?

use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        panic!("boom");
    });
    let result = handle.join();
    println!("{}", result.is_err());
}

Capturing Data with move

7.

What does this print?

use std::thread;

fn main() {
    let numbers = vec![1, 2, 3, 4];
    let handle = thread::spawn(move || numbers.iter().sum::<i32>());
    println!("{}", handle.join().unwrap());
}
8.

Does this compile?

use std::thread;

fn main() {
    let numbers = vec![1, 2, 3];
    let handle = thread::spawn(|| {
        println!("{:?}", numbers);
    });
    handle.join().unwrap();
}
9.

numbers is used once more after it is moved into the closure. Does this compile?

use std::thread;

fn main() {
    let numbers = vec![1, 2, 3];
    let handle = thread::spawn(move || {
        println!("{:?}", numbers);
    });
    handle.join().unwrap();
    println!("{:?}", numbers);
}
10.

What does this print?

use std::thread;

fn main() {
    let first = String::from("Grace");
    let last = String::from("Hopper");
    let handle = thread::spawn(move || format!("{first} {last}"));
    println!("{}", handle.join().unwrap());
}
11.

i32 implements Copy, unlike Vec in question 9. Does this compile, and what does it print?

use std::thread;

fn main() {
    let n = 5;
    let handle = thread::spawn(move || n + 1);
    println!("{}", handle.join().unwrap());
    println!("{n}");
}
12.

What does this print?

use std::thread;

fn main() {
    let message = String::from("hello");
    let mut handles = vec![];

    for _ in 0..3 {
        let message = message.clone();
        handles.push(thread::spawn(move || message.len()));
    }

    let mut total = 0;
    for handle in handles {
        total += handle.join().unwrap();
    }
    println!("{total}");
}

Threads Run Independently

13.

This program does not have one fixed output. Does it compile, and why can't the order of the two lines be predicted?

use std::thread;

fn main() {
    thread::spawn(|| {
        println!("worker");
    });
    println!("boss");
}
14.

This program joins a but never joins the second thread. Which lines are guaranteed to print?

use std::thread;

fn main() {
    let a = thread::spawn(|| println!("a finished"));
    thread::spawn(|| println!("b finished"));
    a.join().unwrap();
    println!("main finished");
}
15.

Unlike question 13, this program has one fixed order of output. What does it print?

use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        println!("worker");
    });
    handle.join().unwrap();
    println!("boss");
}

Sharing State with Arc<T> and Mutex<T>

16.

What does this print?

use std::sync::Mutex;

fn main() {
    let value = Mutex::new(0);
    *value.lock().unwrap() += 1;
    *value.lock().unwrap() += 1;
    println!("{}", value.lock().unwrap());
}
17.

What does this print?

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let total = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..5 {
        let total = Arc::clone(&total);
        handles.push(thread::spawn(move || {
            *total.lock().unwrap() += 10;
        }));
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("{}", total.lock().unwrap());
}
18.

Arc keeps a count the same way Rc does. What does this print?

use std::sync::Arc;

fn main() {
    let n = Arc::new(5);
    let a = Arc::clone(&n);
    let b = Arc::clone(&n);
    println!("{}", Arc::strong_count(&n));
}
19.

What does this print?

use std::sync::Mutex;

fn main() {
    let m = Mutex::new(10);
    {
        let mut guard = m.lock().unwrap();
        *guard += 5;
    }
    println!("{}", m.lock().unwrap());
}
20.

What does this print?

use std::sync::{Arc, Mutex};

struct Inventory {
    count: Mutex<i32>,
}

fn restock(inv: &Arc<Inventory>, amount: i32) {
    *inv.count.lock().unwrap() += amount;
}

fn main() {
    let inv = Arc::new(Inventory { count: Mutex::new(0) });
    let a = Arc::clone(&inv);
    let b = Arc::clone(&inv);

    restock(&a, 3);
    restock(&b, 7);

    println!("{}", inv.count.lock().unwrap());
}
21.

Mutex has no method named push; only the Vec locked inside it does. Does this compile?

use std::sync::Mutex;

fn main() {
    let count = Mutex::new(vec![1, 2, 3]);
    count.push(4);
    println!("{:?}", count.lock().unwrap());
}
22.

drop(guard) releases the lock early. What does this print?

use std::sync::Mutex;

fn main() {
    let n = Mutex::new(1);

    let guard = n.lock().unwrap();
    println!("{guard}");
    drop(guard);

    *n.lock().unwrap() += 1;
    println!("{}", n.lock().unwrap());
}
23.

What does this print?

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let names = Arc::new(Mutex::new(Vec::new()));

    let a = Arc::clone(&names);
    let handle_a = thread::spawn(move || {
        a.lock().unwrap().push("first");
    });
    handle_a.join().unwrap();

    let b = Arc::clone(&names);
    let handle_b = thread::spawn(move || {
        b.lock().unwrap().push("second");
    });
    handle_b.join().unwrap();

    println!("{:?}", names.lock().unwrap());
}

Message Passing with Channels

24.

What does this print?

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        for n in 1..=3 {
            tx.send(n).unwrap();
        }
    });

    for received in rx {
        println!("{received}");
    }
}
25.

What does this print?

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        tx.send("first").unwrap();
        tx.send("second").unwrap();
    });

    println!("{}", rx.recv().unwrap());
    println!("{}", rx.recv().unwrap());
}
26.

What does this print?

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let message = String::from("built on another thread");
        tx.send(message).unwrap();
    });

    println!("{}", rx.recv().unwrap());
}
27.

tx is moved into the closure, then used again on the next line. Does this compile?

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        tx.send(1).unwrap();
    });
    tx.send(2).unwrap();

    println!("{:?}", rx.recv());
}
28.

What does this print?

use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel::<i32>();
    drop(tx);

    match rx.recv() {
        Ok(v) => println!("{v}"),
        Err(_) => println!("closed"),
    }
}
29.

What does this print?

use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();
    drop(rx);

    match tx.send(5) {
        Ok(()) => println!("sent"),
        Err(_) => println!("no receiver"),
    }
}
30.

Three threads send at nearly the same moment, so the values are collected and sorted rather than printed as they arrive. What does this print?

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    let mut handles = vec![];
    for id in 0..4 {
        let tx = tx.clone();
        handles.push(thread::spawn(move || {
            tx.send(id).unwrap();
        }));
    }
    drop(tx);

    for handle in handles {
        handle.join().unwrap();
    }

    let mut received: Vec<i32> = rx.iter().collect();
    received.sort();
    println!("{received:?}");
}
31.

This program compiles, but it never finishes. Which sender is still alive and keeps the for loop waiting?

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    for id in 0..3 {
        let tx = tx.clone();
        thread::spawn(move || {
            tx.send(id).unwrap();
        });
    }

    for received in rx {
        println!("{received}");
    }
}
32.

What does this print?

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        for n in 1..=5 {
            tx.send(n).unwrap();
        }
    });

    let total: i32 = rx.iter().sum();
    println!("{total}");
}
33.

Rc is not Send, and sending one through a channel to another thread moves it there just as directly as capturing it in a move closure would. Does this compile?

use std::rc::Rc;
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    let value = Rc::new(5);

    thread::spawn(move || {
        tx.send(value).unwrap();
    });

    println!("{:?}", rx.recv());
}

The Send and Sync Traits

34.

Does this compile?

use std::rc::Rc;
use std::thread;

fn main() {
    let numbers = Rc::new(vec![1, 2, 3]);

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

    handle.join().unwrap();
}
35.

RefCell is Send but not Sync: only one thread ever owns n here, it is never shared. Does this compile, and what does it print?

use std::cell::RefCell;
use std::thread;

fn main() {
    let n = RefCell::new(0);

    let handle = thread::spawn(move || {
        *n.borrow_mut() += 1;
        n
    });

    let n = handle.join().unwrap();
    println!("{}", n.borrow());
}
36.

Does this compile?

use std::cell::RefCell;
use std::sync::Arc;
use std::thread;

fn main() {
    let shared = Arc::new(RefCell::new(0));
    let clone = Arc::clone(&shared);

    let handle = thread::spawn(move || {
        *clone.borrow_mut() += 1;
    });

    handle.join().unwrap();
    println!("{}", shared.borrow());
}
37.

This is question 36 with RefCell replaced by Mutex. What does it print?

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let shared = Arc::new(Mutex::new(0));
    let clone = Arc::clone(&shared);

    let handle = thread::spawn(move || {
        *clone.lock().unwrap() += 1;
    });

    handle.join().unwrap();
    println!("{}", shared.lock().unwrap());
}
38.

i32 is Sync, so several threads may read the same Arc<i32> with no Mutex at all. What does this print?

use std::sync::Arc;
use std::thread;

fn main() {
    let shared = Arc::new(42);
    let mut handles = vec![];

    for _ in 0..3 {
        let shared = Arc::clone(&shared);
        handles.push(thread::spawn(move || *shared));
    }

    let mut total = 0;
    for handle in handles {
        total += handle.join().unwrap();
    }
    println!("{total}");
}
39.

Box<T> is Send whenever T is, unlike Rc<T>, which is never Send. Does this compile, and what does it print?

use std::thread;

fn main() {
    let boxed = Box::new(10);
    let handle = thread::spawn(move || *boxed + 1);
    println!("{}", handle.join().unwrap());
}

Mixed Review

40.

What does this print?

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    let mut handles = vec![];
    for n in 1..=3 {
        let tx = tx.clone();
        handles.push(thread::spawn(move || {
            tx.send(n * n).unwrap();
        }));
    }
    drop(tx);

    for handle in handles {
        handle.join().unwrap();
    }

    let mut results: Vec<i32> = rx.iter().collect();
    results.sort();
    println!("{results:?}");
}
41.

data is moved into the thread whole, never shared, so no Arc is needed. What does this print?

use std::sync::Mutex;
use std::thread;

fn main() {
    let data = Mutex::new(vec![1, 2, 3]);

    let handle = thread::spawn(move || {
        data.lock().unwrap().push(4);
        data
    });

    let data = handle.join().unwrap();
    println!("{:?}", data.lock().unwrap());
}
42.

Mutex does not implement Clone, on purpose: cloning would give two independent locks guarding what looks like one shared value. Does this compile?

use std::sync::Mutex;
use std::thread;

fn main() {
    let data = Mutex::new(0);
    let copy = data.clone();

    let handle = thread::spawn(move || {
        *copy.lock().unwrap() += 1;
    });

    handle.join().unwrap();
    println!("{}", data.lock().unwrap());
}
43.

Why can locking two Mutex values in a different order on each thread hang forever?

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let a = Arc::new(Mutex::new(1));
    let b = Arc::new(Mutex::new(2));

    let a1 = Arc::clone(&a);
    let b1 = Arc::clone(&b);
    let t1 = thread::spawn(move || {
        let _x = a1.lock().unwrap();
        let _y = b1.lock().unwrap();
    });

    let a2 = Arc::clone(&a);
    let b2 = Arc::clone(&b);
    let t2 = thread::spawn(move || {
        let _y = b2.lock().unwrap();
        let _x = a2.lock().unwrap();
    });

    t1.join().unwrap();
    t2.join().unwrap();
}
44.

What does this print?

use std::sync::{Arc, Mutex};
use std::thread;

struct Tasks {
    done: Mutex<Vec<i32>>,
}

impl Tasks {
    fn complete(&self, id: i32) {
        self.done.lock().unwrap().push(id);
    }
}

fn main() {
    let tasks = Arc::new(Tasks { done: Mutex::new(vec![]) });
    let mut handles = vec![];

    for id in 0..3 {
        let tasks = Arc::clone(&tasks);
        handles.push(thread::spawn(move || {
            tasks.complete(id);
        }));
    }

    for handle in handles {
        handle.join().unwrap();
    }

    let mut done = tasks.done.lock().unwrap().clone();
    done.sort();
    println!("{done:?}");
}
45.

RefCell was refused earlier in this lesson when it was shared through an Arc. Here it is only ever owned by one side at a time: first the spawned thread, then main. Does this compile?

use std::cell::RefCell;
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    let cell = RefCell::new(5);

    thread::spawn(move || {
        *cell.borrow_mut() += 1;
        tx.send(cell).unwrap();
    });

    let cell = rx.recv().unwrap();
    println!("{}", cell.borrow());
}