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 starts a new thread in Rust.
Complete the code to wait for the thread to finish execution.
use std::thread;
fn main() {
let handle = thread::spawn(|| {
println!("Thread is running");
});
handle.[1]().unwrap();
}The join() method waits for the thread to finish and returns its result.
Fix the error in the code to correctly share data between threads using Arc.
use std::sync::[1]; use std::sync::Arc; use std::thread; fn main() { let counter = Arc::new([2]::new(0)); let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handle.join().unwrap(); println!("Counter: {}", *counter.lock().unwrap()); }
To share mutable data safely between threads, Rust uses Arc for shared ownership and Mutex for mutual exclusion.
Fill both blanks to create a thread that increments a shared counter safely.
use std::sync::{Arc, [1];
use std::thread;
fn main() {
let counter = Arc::new([2]::new(0));
let counter_clone = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter_clone.lock().unwrap();
*num += 1;
});
handle.join().unwrap();
println!("Counter: {}", *counter.lock().unwrap());
}Mutex is used to protect shared data, and Arc allows multiple ownership across threads.
Fill all three blanks to create multiple threads that increment a shared counter safely.
use std::sync::{Arc, [1];
use std::thread;
fn main() {
let counter = Arc::new([2]::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.[3]().unwrap();
}
println!("Final counter: {}", *counter.lock().unwrap());
}Use Mutex to protect the counter, Arc for shared ownership, and join() to wait for threads to finish.