0
0
Rustprogramming~20 mins

Threads overview in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rust Threads Mastery
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!\nHello from the thread!
BHello from the thread!\nHello from the main thread!
CHello from the thread!
DHello from the main thread!
Attempts:
2 left
💡 Hint

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

🧠 Conceptual
intermediate
1:30remaining
Which statement about Rust threads is true?

Choose the correct statement about Rust threads.

ARust threads require explicit synchronization to share data safely.
BRust threads automatically clone all variables from the main thread.
CRust threads cannot be joined once spawned.
DRust threads share memory by default without any safety checks.
Attempts:
2 left
💡 Hint

Think about Rust's ownership and safety guarantees.

🔧 Debug
advanced
2:30remaining
What error does this Rust thread code produce?

Examine the code below. What error will the Rust compiler report?

Rust
use std::thread;

fn main() {
    let v = vec![1, 2, 3];
    let handle = thread::spawn(|| {
        println!("{:?}", v);
    });
    handle.join().unwrap();
}
ANo error, prints [1, 2, 3]
Berror: use of moved value `v`
Cerror: closure may outlive the current function, but it borrows `v`, which is owned by the current function
Derror: expected `FnOnce` closure, found `FnMut` closure
Attempts:
2 left
💡 Hint

Think about how closures capture variables and thread lifetimes.

Predict Output
advanced
2:00remaining
What is the output of this Rust thread code with move closure?

What will this Rust program print?

Rust
use std::thread;

fn main() {
    let v = vec![10, 20, 30];
    let handle = thread::spawn(move || {
        println!("{:?}", v);
    });
    handle.join().unwrap();
}
Aerror: use of moved value `v`
Berror: closure does not implement `FnOnce`
C[]
D[10, 20, 30]
Attempts:
2 left
💡 Hint

Consider what the move keyword does to variable capture.

🧠 Conceptual
expert
1:30remaining
Which Rust synchronization primitive allows multiple threads to read but only one to write at a time?

Choose the synchronization primitive that permits multiple readers or one writer concurrently.

ARwLock
BAtomicBool
CMutex
DCondvar
Attempts:
2 left
💡 Hint

Think about read-write locks.