How to Achieve Multithreading in Rust
ChatGPTHendo
Sign in to confirm0 confirmations
Question
The developer is seeking information on how to create multiple threads in a Rust program, ensuring memory safety and performance.
Answer
Rust provides a strong foundation for multithreading through its ownership system and standard library. The `std::thread` module allows for thread creation, and the `Arc` and `Mutex` types facilitate synchronization and shared state management between threads. Channels can also be used for message passing.
rust
use std::thread; fn main() { let handle = thread::spawn(|| { println!("Hello from another thread!"); }); handle.join().unwrap(); }rust
use std::sync::{Arc, Mutex}; use std::thread; fn main() { let counter = Arc::new(Mutex::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.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); }concurrencyrustmultithreadingmemorysafety