Is the join() necessary when using a channel?

Hi Rust experts, is the join() necessary when using a channel in the example hereunder?

Coming from Go, the join() operation seems overkill, but maybe it is necessary with Rust?

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


static NTHREADS: i32 = 3;

fn main() {
    
    // Channel:
    let (tx, rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();
    
    // Vector (for holding the NTHREADS thread handles):
    let mut children = Vec::new();

    for id in 0..NTHREADS {
        let thread_tx = tx.clone();
        let child = thread::spawn(move || {
            thread::sleep(time::Duration::from_millis(100));
            thread_tx.send(id).unwrap();
            println!("thread {} finished", id);
        });
        children.push(child);
    }

    for _ in 0..NTHREADS {
        println!("{:?}", rx.recv())
    }
    
    // Join all the threads: 
    for child in children {
        child.join().expect("oops! the child thread panicked");
    }

    println!("Main thread done")

}

Joining a thread is not required. However, your spawned threads will not survive the end of the main thread, which means without it, the println!() after thread_tx.send() may or may not get a chance to run.

1 Like

The join is not necessary. I put a console read at the end of my main.rs to keep it from exiting.

1 Like