Introduction
In this lab, we have a code snippet in Rust that demonstrates how to spawn native OS threads using the spawn function and a moving closure. The code creates a vector to hold the spawned threads, iterates through a range of numbers to spawn multiple threads, and prints a message identifying each thread number. Finally, the main thread waits for each spawned thread to finish using the join function.
Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use
main.rs, compile and run it withrustc main.rs && ./main.
Threads
Rust provides a mechanism for spawning native OS threads via the spawn function, the argument of this function is a moving closure.
use std::thread;
const NTHREADS: u32 = 10;
// This is the `main` thread
fn main() {
// Make a vector to hold the children which are spawned.
let mut children = vec![];
for i in 0..NTHREADS {
// Spin up another thread
children.push(thread::spawn(move || {
println!("this is thread number {}", i);
}));
}
for child in children {
// Wait for the thread to finish. Returns a result.
let _ = child.join();
}
}
These threads will be scheduled by the OS.
Summary
Congratulations! You have completed the Threads lab. You can practice more labs in LabEx to improve your skills.