Share data between Rust threads safely using std::sync::mpsc channels to move ownership.
Use std::sync::mpsc channels to send data between threads safely by moving ownership across thread boundaries.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
}
Sharing data between threads in Rust lets one thread send a message to another without them sharing memory directly. Think of it like passing a note through a tube: the sender puts the note in, and the receiver takes it out, ensuring only one person holds the note at a time. You use this when you need to coordinate work between different parts of your program running at the same time.