Channels in Rust Programming

Rust ProgrammingServer Side ProgrammingProgramming

Channels are a medium that allow communication to take place between two or more threads. Rust provides asynchronous channels that enable communication between threads.

Channels in Rust allow a unidirectional flow of communication between two endpoints. These two endpoints are Sender and Receiver.

Example

Consider the example shown below −

use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::thread;

static NTHREADS: i32 = 3;

fn main() {
   let (tx, rx): (Sender, Receiver) = mpsc::channel();
   let mut children = Vec::new();
   for id in 0..NTHREADS {
      let thread_tx = tx.clone();
      let child = thread::spawn(move || {
         thread_tx.send(id).unwrap();
         println!("thread {} done", id);
      });
      children.push(child);
   }
   let mut ids = Vec::with_capacity(NTHREADS as usize);
   for _ in 0..NTHREADS {
      ids.push(rx.recv());
   }
   for child in children {
      child.join().expect("oops! the child thread stopped working");
   }
   println!("{:?}", ids);
}

In the above code, we are trying to pass the id of the thread to the other thread via a channel.

Output

When we run the above code, we will see this output:

thread 0 done
thread 1 done
thread 2 done
[Ok(0), Ok(1), Ok(2)]

The output implies that all the threads worked perfectly and the communication was enabled between them via a channel.

raja
Published on 03-Apr-2021 12:40:21
Advertisements