Threads and message passing with channels
Concurrency, doing several things "at once", is famous for producing bugs that are very hard to find: two threads modifying the same data, results that change on every run, deadlocks that appear once a month. Rust attacks the problem with the same ownership rules you already know: the compiler rejects programs with data races. That is why Rust is said to offer "fearless concurrency". In this lesson you will see how to create threads and how to make them communicate by sending messages.
Creating threads with thread::spawn
std::thread::spawn takes a closure and runs it in a new operating system thread. It returns a JoinHandle; by calling join() you wait for the thread to finish and get its result (inside a Result, because the thread might have panicked). If main ends before the threads, they stop without finishing, so you almost always need to join. The order in which threads print is not guaranteed: the operating system decides it and it may vary each time.
use std::thread;
fn main() {
let handle = thread::spawn(|| {
let mut total = 0u64;
for i in 1..=1000 {
total += i;
}
total // the value returned by the thread
});
println!("main keeps working...");
let result = handle.join().unwrap();
println!("thread result = {result}");
// `move` gives the thread ownership of the data it uses
let data = vec![1, 2, 3];
let h = thread::spawn(move || {
println!("thread sees {:?}", data);
data.len()
});
println!("len = {}", h.join().unwrap());
// println!("{:?}", data); // error: data was moved into the thread
}Notice the use of move. A thread can outlive the function that created it, so it cannot borrow local variables: you must give them to it with move. After that, main can no longer use data. It is the ownership system preventing two threads from sharing a piece of data without control: either it belongs to one, or it is shared with the tools you will see in the next lesson.
Channels: mpsc
A safe way to communicate threads is to send messages, following the motto "do not communicate by sharing memory; share memory by communicating". std::sync::mpsc (multiple producer, single consumer) creates a channel with two ends: the Sender (tx), which can be cloned to have several producers, and the Receiver (rx), which is unique. tx.send(value) moves the value into the channel, so the sender can no longer use it, and rx.recv() waits until it receives something. The receiver can also be walked with for: it ends when all senders have been dropped.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
let mut workers = Vec::new();
for id in 1..=3 {
let tx = tx.clone(); // one sender per worker
workers.push(thread::spawn(move || {
let square = id * id;
tx.send((id, square)).unwrap();
}));
}
drop(tx); // close the original sender, otherwise the loop below never ends
let mut results: Vec<(i32, i32)> = Vec::new();
for message in rx {
results.push(message);
}
for w in workers {
w.join().unwrap();
}
results.sort(); // arrival order is not guaranteed
println!("{:?}", results);
}An important consequence of send moving the value: if you send a String, the sending thread can no longer use it, so there is no way for two threads to modify the same data at once. When a thread instead needs to read or write shared state, other tools are needed, such as Arc and Mutex, which we will see next. Another detail: recv() blocks; if you do not want to wait, try_recv() returns immediately an Err if there is no message, and recv_timeout lets you wait for a maximum time.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
for n in [10u32, 20, 30, 40] {
let tx = tx.clone();
thread::spawn(move || {
let sum: u32 = (1..=n).sum();
tx.send((n, sum)).unwrap();
});
}
drop(tx);
let mut results: Vec<(u32, u32)> = rx.iter().collect();
results.sort();
for (n, sum) in results {
println!("({n}, {sum})");
}
}जो सीखा उसे परखें
प्रश्न 1 / 4What does handle.join() do?
✎ मेरे नोट्स
केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर