| In Rust, you implement a threaded application using the std::thread module. You create new threads using the thread::spawn function, passing a closure or function as an argument that represents the thread's task. This closure receives ownership of any data it needs. Threads communicate through channels (using mpsc or similar) for passing data between them, avoiding data races through proper ownership and borrowing. When the spawned threads finish, you can join them using the join() method to retrieve their results, ensuring that the main thread waits for completion if needed. Error handling is crucial; panics in threads need to be handled gracefully, often by using a Result type within the thread's function. Here’s a simple example of using threads in Rust, demonstrating how to perform concurrent tasks. use std::thread;
use std::time::Duration;
fn main() {
let handle1 = thread::spawn(|| {
for i in 1..5 {
println!("Thread 1 - Count: {}", i);
thread::sleep(Duration::from_millis(500)); // Simulate work
}
});
let handle2 = thread::spawn(|| {
for i in 1..5 {
println!("Thread 2 - Count: {}", i);
thread::sleep(Duration::from_millis(400)); // Simulate work
}
});
for i in 1..5 {
println!("Main Thread - Count: {}", i);
thread::sleep(Duration::from_millis(300));
}
// Wait for the threads to finish
handle1.join().unwrap();
handle2.join().unwrap();
println!("All threads completed.");
}
Explanation- Thread Creation:
thread::spawn starts a new thread and executes the closure provided.
- Simulating Work:
thread::sleep(Duration::from_millis(...)) is used to mimic a delay, representing work being done by the threads.
- Main Thread:
- The main thread continues executing alongside the spawned threads.
- Thread Synchronization:
handle.join() ensures the main thread waits for the spawned threads to complete before exiting.
Output ExampleThe exact order of the output may vary due to concurrent execution: Main Thread - Count: 1
Thread 1 - Count: 1
Thread 2 - Count: 1
Main Thread - Count: 2
Thread 1 - Count: 2
Thread 2 - Count: 2
Main Thread - Count: 3
Thread 1 - Count: 3
Thread 2 - Count: 3
Main Thread - Count: 4
Thread 1 - Count: 4
Thread 2 - Count: 4
All threads completed.
This example demonstrates Rust's ability to handle threads safely and efficiently. Each thread runs independently, and the main thread ensures they complete before the program exits using the join method. |