What does this print?
use std::thread;
fn main() {
let handle = thread::spawn(|| 10 + 20);
println!("{}", handle.join().unwrap());
}Running it prints:
30
Practice 14
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.
0 of 45 answered·0 correct
std::threadWhat does this print?
use std::thread;
fn main() {
let handle = thread::spawn(|| 10 + 20);
println!("{}", handle.join().unwrap());
}Running it prints:
30
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}");
}Running it prints:
inside the thread result: 99
What does this print?
use std::thread;
fn main() {
let handle = thread::spawn(|| String::from("done"));
println!("{}", handle.join().unwrap());
}Running it prints:
done
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();
}Running it prints:
first second
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());
}Running it prints:
30
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());
}Running it prints:
true
moveWhat 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());
}Running it prints:
10
Does this compile?
use std::thread;
fn main() {
let numbers = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("{:?}", numbers);
});
handle.join().unwrap();
}The compiler says:
error[E0373]: closure may outlive the current function, but it borrows `numbers`, which is owned by the current function
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);
}The compiler says:
error[E0382]: borrow of moved value: `numbers`
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());
}Running it prints:
Grace Hopper
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}");
}Running it prints:
6 5
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}");
}Running it prints:
15
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");
}Runs here printed only boss: main returned before the worker got a turn.
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");
}Returning from main ends the program, even while other threads are still running.
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");
}Running it prints:
worker boss
Arc<T> and Mutex<T>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());
}Running it prints:
2
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());
}Running it prints:
50
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));
}Running it prints:
3
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());
}Running it prints:
15
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());
}Running it prints:
10
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());
}The compiler says:
error[E0599]: no method named `push` found for struct `std::sync::Mutex<T>` in the current scope
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());
}Running it prints:
1 2
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());
}Running it prints:
["first", "second"]
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}");
}
}Running it prints:
1 2 3
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());
}Running it prints:
first second
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());
}Running it prints:
built on another thread
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());
}The compiler says:
error[E0382]: borrow of moved value: `tx`
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"),
}
}Running it prints:
closed
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"),
}
}Running it prints:
no receiver
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:?}");
}Running it prints:
[0, 1, 2, 3]
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}");
}
}The program prints 0, 1 and 2 in some order and then waits forever. drop(tx); before the loop fixes it.
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}");
}Running it prints:
15
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 compiler says:
error[E0277]: `Rc<i32>` cannot be sent between threads safely
Send and Sync TraitsDoes 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();
}The compiler says:
error[E0277]: `Rc<Vec<i32>>` cannot be sent between threads safely
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());
}Running it prints:
1
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());
}The compiler says:
error[E0277]: `RefCell<i32>` cannot be shared between threads safely
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());
}Running it prints:
1
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}");
}Running it prints:
126
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());
}Running it prints:
11
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:?}");
}Running it prints:
[1, 4, 9]
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());
}Running it prints:
[1, 2, 3, 4]
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());
}The compiler says:
error[E0599]: no method named `clone` found for struct `std::sync::Mutex<T>` in the current scope
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();
}This is a deadlock. Locking in the same order on every thread prevents it.
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:?}");
}Running it prints:
[0, 1, 2]
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());
}Running it prints:
6