rustHow to communicate between threads in Rust?
Threads in Rust can communicate through channels. Channels are a type of synchronization primitive that allows one thread to send data to another thread.
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
// Sending a message
tx.send(42).unwrap();
// Receiving a message
let received = rx.recv().unwrap();
println!("Received {}", received);
// Output: Received 42
use std::sync::mpsc;
: imports the mpsc (multiple producer, single consumer) module from the standard library.let (tx, rx) = mpsc::channel();
: creates a new channel and returns a pair of sender (tx) and receiver (rx) endpoints.tx.send(42).unwrap();
: sends the value 42 from the sender (tx) to the receiver (rx).let received = rx.recv().unwrap();
: receives the value 42 from the receiver (rx).println!("Received {}", received);
: prints the received value.
Helpful links
More of Rust
- How to get a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to use regex with bytes in Rust?
- How to match whitespace with a regex in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to replace strings using Rust regex?
- How to parse JSON string in Rust?
- How to use regex to match a group in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
See more codes...