Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rust

How to pass messages to transfer data between threads

Mohe Ud Din Sheikh

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 myfunc
fn 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 1
    thread::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 2 
    thread::spawn(move || {
        

        for val in vals2 {
            tx.send(val).unwrap();
            thread::sleep(Duration::from_secs(1));
        }
    });
    // use loop to get all the messages from threads
    for received in rx {
        println!("Get: {}", received);
    }
}

fn main() {
    //call the myfunc function

    myfunc();

}

Explanation

  • Lines 5–13: We declare a function, myfunc. After declaring the function, we declare tx and rx which will be used as a channel for communication. We also declare a vals1 variable that stores messages.
  • Lines 15–21: We declare a thread using thread::spawn. We use the vals1 variable 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 vals2 values as messages.
  • Lines 39–41: We use a for loop to get all the messages from the thread.
  • Line 46: At the end, we call the myfunc function for communication.

RELATED TAGS

rust

CONTRIBUTOR

Mohe Ud Din Sheikh
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring