How to pass messages to transfer data between threads
Overview
In Rust, we can achieve the safe passing of messages between threads using a channel. A channel is a communication medium that transmits a message between two halves—a transmitter and a receiver. The transmitter end sends a message, while the receiver end is constantly scanning for messages from the transmission end. When the receiver receives a message, it forwards it to the thread that is using the receiver end. Let's explore a program example for a better understanding of this.
Example
use std::sync::mpsc;use std::thread;use std::time::Duration;//Declaring a function with the name of myfuncfn myfunc(){let (tx, rx) = mpsc::channel();let tx1 = tx.clone();let vals1 = vec![String::from("Thread 1:Hi "),String::from("Thread 1:Thread 2 ?"),];// Created Thread 1thread::spawn(move || {for val in vals1 {tx1.send(val).unwrap();thread::sleep(Duration::from_secs(1));}});let vals2 = vec![String::from("Thread 2:Hi"),String::from("Thread 2: Yes"),];//Created thread 2thread::spawn(move || {for val in vals2 {tx.send(val).unwrap();thread::sleep(Duration::from_secs(1));}});// use loop to get all the messages from threadsfor received in rx {println!("Get: {}", received);}}fn main() {//call the myfunc functionmyfunc();}
Explanation
- Lines 5–13: We declare a function,
myfunc. After declaring the function, we declaretxandrxwhich will be used as a channel for communication. We also declare avals1variable that stores messages. - Lines 15–21: We declare a thread using
thread::spawn. We use thevals1variable as a message of the first thread. - Lines 23–28: We declare a new variable,
vals2. This stores the vector that will be used as a message of the second thread. - Lines 30–37: We declare a second thread in which we use the
vals2values as messages. - Lines 39–41: We use a
forloop to get all the messages from the thread. - Line 46: At the end, we call the
myfuncfunction for communication.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved