Concurrency & Thread Communication
Rust guarantees safe concurrency. The compiler prevents data races at compile time, ensuring thread safety before your code ever runs.
1 OS Threads, the move keyword, and mpsc Channels
Rust concurrency follows strict safety rules:
- thread::spawn: Spawns a native OS thread.
- move keyword: Forces the spawned thread to take ownership of captured variables, preventing dangling references.
- mpsc Channels: Multi-producer, single-consumer channel communication pipelines, allowing threads to send and receive data safely without shared-memory locks.
2 Concurrency Code
Let's run a program spawning threads and sending data through mpsc channels:
Rust — Threads & Channels
▶ Run Code
use std::thread;
use std::sync::mpsc; // Multi-producer, single-consumer channels
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
// Spawn a thread and move ownership of tx into it
thread::spawn(move || {
let msg = String::from("Greetings from spawned thread!");
thread::sleep(Duration::from_millis(50));
tx.send(msg).unwrap(); // Send message into channel
});
// Receive message in main thread (blocks execution until data is sent)
let received = rx.recv().unwrap();
println!("Received in Main: {}", received);
}
3 Code Challenge
Challenge: Spawn a thread that counts from 1 to 5. Sleep for 100 milliseconds between prints. Ensure you use the `move` keyword to pass captured thread variables.