0
0
Rustprogramming~10 mins

Creating threads in Rust - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a new thread that prints "Hello from thread!".

Rust
use std::thread;

fn main() {
    let handle = thread::[1](|| {
        println!("Hello from thread!");
    });

    handle.join().unwrap();
}
Drag options to blanks, or click blank then click option'
Aspawn
Bstart
Crun
Dcreate
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent function like 'start' or 'create' instead of 'spawn'.
Forgetting to call join() to wait for the thread to finish.
2fill in blank
medium

Complete the code to move ownership of the variable data into the new thread.

Rust
use std::thread;

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

    let handle = thread::spawn(move || {
        println!("Data: {:?}", [1]);
    });

    handle.join().unwrap();
}
Drag options to blanks, or click blank then click option'
Adata
Bdata.clone()
C&data
Dref data
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to borrow data with &data inside a move closure.
Using data.clone() unnecessarily.
3fill in blank
hard

Fix the error in the code by completing the blank to properly handle the thread's result.

Rust
use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        5 + 10
    });

    let result = handle.[1]().unwrap();
    println!("Result: {}", result);
}
Drag options to blanks, or click blank then click option'
Afinish
Bwait
Cjoin
Dcomplete
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like wait or finish.
Not calling unwrap() to get the thread's result.
4fill in blank
hard

Fill both blanks to create multiple threads that print their index.

Rust
use std::thread;

fn main() {
    let mut handles = vec![];

    for i in 0..3 {
        let handle = thread::spawn([1] || {
            println!("Thread number: {}", [2]);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
}
Drag options to blanks, or click blank then click option'
Amove
Bi + 1
Ci
Dref
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting move causes borrowing errors.
Using i + 1 changes the thread number unexpectedly.
5fill in blank
hard

Fill all three blanks to create a thread that returns the length of a string.

Rust
use std::thread;

fn main() {
    let text = String::from("hello");

    let handle = thread::[1](move || {
        [2].len()
    });

    let length = handle.[3]().unwrap();
    println!("Length: {}", length);
}
Drag options to blanks, or click blank then click option'
Aspawn
Btext
Cjoin
Drun
Attempts:
3 left
💡 Hint
Common Mistakes
Using run instead of spawn.
Not moving text into the closure.
Forgetting to call join().