Complete the code to create a new thread that prints "Hello from thread!".
use std::thread;
fn main() {
let handle = thread::[1](|| {
println!("Hello from thread!");
});
handle.join().unwrap();
}The thread::spawn function creates a new thread and runs the given closure inside it.
Complete the code to move ownership of the variable data into the new thread.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("Data: {:?}", [1]);
});
handle.join().unwrap();
}data with &data inside a move closure.data.clone() unnecessarily.The move keyword transfers ownership of data into the thread, so you can use data directly inside the closure.
Fix the error in the code by completing the blank to properly handle the thread's result.
use std::thread;
fn main() {
let handle = thread::spawn(|| {
5 + 10
});
let result = handle.[1]().unwrap();
println!("Result: {}", result);
}wait or finish.unwrap() to get the thread's result.The join() method waits for the thread to finish and returns the result of the thread's closure.
Fill both blanks to create multiple threads that print their index.
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();
}
}move causes borrowing errors.i + 1 changes the thread number unexpectedly.The move keyword moves the variable i into the thread closure. Using i inside the closure prints the thread's index.
Fill all three blanks to create a thread that returns the length of a string.
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);
}run instead of spawn.text into the closure.join().thread::spawn creates the thread, text is moved into the closure, and join() waits for the thread to finish and returns the result.