Consider the following Rust program that creates a thread and prints a message. What will it print?
use std::thread;
fn main() {
let handle = thread::spawn(|| {
println!("Hello from the thread!");
});
handle.join().unwrap();
println!("Hello from the main thread!");
}Remember that join() waits for the thread to finish before continuing.
The spawned thread prints its message first. The main thread waits for it to finish by calling join(), then prints its own message.
Look at this Rust program that spawns a thread but does not join it. What will be the output?
use std::thread;
use std::time::Duration;
fn main() {
thread::spawn(|| {
thread::sleep(Duration::from_millis(50));
println!("Thread done");
});
println!("Main done");
}The main thread may finish before the spawned thread prints anything.
Because the main thread does not wait for the spawned thread, the program may end before the spawned thread runs its print statement.
Examine this Rust code that tries to spawn a thread using a variable from the main thread. Why does it fail to compile?
use std::thread;
fn main() {
let s = String::from("hello");
let handle = thread::spawn(|| {
println!("{}", s);
});
handle.join().unwrap();
}Think about how variables are captured by closures when spawning threads.
Rust requires the closure passed to thread::spawn to have the move keyword to take ownership of captured variables. Without move, the closure tries to borrow 's', which is not allowed because the thread may outlive the main function's stack frame.
Choose the code snippet that correctly creates 3 threads, each printing its index, and waits for all to finish.
Remember to use move to capture the loop variable correctly and to unwrap the join result.
Option C uses move to capture i by value inside the closure, avoiding borrowing issues. It also calls join().unwrap() to handle errors properly.
This Rust program uses thread::scope to spawn threads that borrow a variable. What will it print?
use std::thread;
fn main() {
let data = vec![1, 2, 3];
thread::scope(|s| {
for &num in &data {
s.spawn(|| {
println!("Number: {}", num);
});
}
});
}thread::scope allows threads to borrow variables safely.
The thread::scope function lets spawned threads borrow variables from the stack safely because it waits for all threads to finish before returning. The threads print each number in the vector. The order may vary but usually matches the loop order.