rust armanazi thread spawning
To spawn a new thread in Rust, you can use the std::thread::spawn
function. This function takes a closure as an argument, which represents the code that will be executed in the new thread. Here's an example:
use std::thread;
fn main() {
// Spawn a new thread
let handle = thread::spawn(|| {
// Code to be executed in the new thread
println!("Hello from the new thread!");
});
// Wait for the new thread to finish
handle.join().unwrap();
// Code continues in the main thread
println!("Hello from the main thread!");
}
In this example, thread::spawn
is called with a closure that simply prints a message. The handle
variable is used to keep track of the spawned thread. The join
method is called on the handle to wait for the thread to finish executing before continuing with the main thread.
When the program is run, it will output:
Hello from the new thread!
Hello from the main thread!
Note that the order of the output may vary, as the new thread and the main thread execute concurrently.