multithreading rust example

Rust Multithreading Example

Here's an example of multithreading in Rust:

use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        // Code to be executed in the new thread
        println!("Hello from the new thread!");
    });

    // Code to be executed in the main thread
    println!("Hello from the main thread!");

    // Wait for the new thread to finish
    handle.join().unwrap();
}

In this example, we use the thread::spawn function to create a new thread and pass it a closure that contains the code to be executed in the new thread. The closure prints "Hello from the new thread!".

In the main thread, we print "Hello from the main thread!".

Finally, we use the join method on the handle to wait for the new thread to finish before the program exits.

This example demonstrates the basic usage of multithreading in Rust. Keep in mind that Rust provides powerful abstractions for concurrent programming, such as channels and locks, which can be used to synchronize data between threads and prevent data races.

I hope this example helps! Let me know if you have any further questions.

[1]