0
0
Rustprogramming~20 mins

Creating threads in Rust - Practice Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rust Thread Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Rust thread code?

Consider the following Rust program that creates a thread and prints a message. What will it print?

Rust
use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        println!("Hello from the thread!");
    });
    handle.join().unwrap();
    println!("Hello from the main thread!");
}
AHello from the main thread!
BHello from the thread!\nHello from the main thread!
CHello from the thread!
DHello from the main thread!\nHello from the thread!
Attempts:
2 left
💡 Hint

Remember that join() waits for the thread to finish before continuing.

Predict Output
intermediate
2:00remaining
What happens if you don't join a thread?

Look at this Rust program that spawns a thread but does not join it. What will be the output?

Rust
use std::thread;
use std::time::Duration;

fn main() {
    thread::spawn(|| {
        thread::sleep(Duration::from_millis(50));
        println!("Thread done");
    });
    println!("Main done");
}
AMain done
BThread done\nMain done
CMain done\nThread done
DThread done
Attempts:
2 left
💡 Hint

The main thread may finish before the spawned thread prints anything.

🔧 Debug
advanced
2:00remaining
Why does this Rust thread code fail to compile?

Examine this Rust code that tries to spawn a thread using a variable from the main thread. Why does it fail to compile?

Rust
use std::thread;

fn main() {
    let s = String::from("hello");
    let handle = thread::spawn(|| {
        println!("{}", s);
    });
    handle.join().unwrap();
}
AThe 'join' method is called incorrectly without handling the Result.
BThe variable 's' is not mutable, so it cannot be used inside the thread.
CThe thread::spawn function requires the closure to return a value, but this closure returns nothing.
DThe closure does not have the 'move' keyword, so it cannot capture 's' by value for the thread.
Attempts:
2 left
💡 Hint

Think about how variables are captured by closures when spawning threads.

📝 Syntax
advanced
2:00remaining
Which option correctly creates and joins multiple threads in Rust?

Choose the code snippet that correctly creates 3 threads, each printing its index, and waits for all to finish.

A
let mut handles = vec![];
for i in 0..3 {
    let handle = thread::spawn(|| {
        println!("Thread {}", i);
    });
    handles.push(handle);
}
for handle in handles {
    handle.join().unwrap();
}
B
let mut handles = vec![];
for i in 0..3 {
    let handle = thread::spawn(move || {
        println!("Thread {}", i);
    });
    handles.push(handle);
}
for handle in handles {
    handle.join();
}
C
let mut handles = vec![];
for i in 0..3 {
    let i = i;
    let handle = thread::spawn(move || {
        println!("Thread {}", i);
    });
    handles.push(handle);
}
for handle in handles {
    handle.join().unwrap();
}
D
let mut handles = vec![];
for i in 0..3 {
    let handle = thread::spawn(|| {
        println!("Thread {}", i);
    });
    handles.push(handle);
}
for handle in handles {
    handle.join();
}
Attempts:
2 left
💡 Hint

Remember to use move to capture the loop variable correctly and to unwrap the join result.

🚀 Application
expert
2:00remaining
What is the output of this Rust program using thread::scope?

This Rust program uses thread::scope to spawn threads that borrow a variable. What will it print?

Rust
use std::thread;

fn main() {
    let data = vec![1, 2, 3];
    thread::scope(|s| {
        for &num in &data {
            s.spawn(|| {
                println!("Number: {}", num);
            });
        }
    });
}
ANumber: 1\nNumber: 2\nNumber: 3
BNumber: 3\nNumber: 2\nNumber: 1
CCompilation error due to borrowing 'data' inside threads
DRuntime panic due to data being moved
Attempts:
2 left
💡 Hint

thread::scope allows threads to borrow variables safely.