Threading in Rust
Rust provides safe and efficient support for threading and concurrency. This document explains how to work with threads in Rust and highlights the languageās unique features for managing concurrent code.
Spawning Threads
Rust allows you to spawn threads dynamically using the thread
module in the Standard Library. Here's a basic example:
use std::thread; fn main() { thread::spawn(|| { println!("Hello from a thread!"); }); thread::sleep(std::time::Duration::from_secs(1)); // Allow the thread to run println!("Hello from the main thread!"); }
In Rust, threads run independently of the main thread until joined. To synchronize the main thread with spawned threads, you use .join()
.
Passing Data to Threads
You can pass data into threads by moving ownership of values using the closur
or move
syntax. Rust ensures that data is safely passed and owned to prevent memory issues:
use std::thread; fn main() { let data = "Hello from outside the thread!"; thread::spawn(move || { println!("{}", data); }); }
Always use the move
keyword in closures if you intend to capture variables and own them in the spawned thread.
Synchronization with Mutex
When multiple threads need to access shared data concurrently, use Mutex
from the standard library to ensure safe read/write access.
use std::sync::{Arc, Mutex}; use std::thread; fn main() { // Wrap the data in an Arc and Mutex for thread-safe access let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let