Passing child threads std::sync::mpsc::Sender to child thread

What is the correct way of doing this? only the first send call works in the following code. can't get the second one to work :confused:

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

fn test(sender: Sender<&'static str>) {
	thread::spawn(move || {
		sender.send("level 2");
	});
}

fn main() {
	let (sender, receiver) = channel();
	let sender2 = sender.clone();
	thread::spawn(move || {
		sender2.send("level 1");
		test(sender2);
	});
	thread::sleep(Duration::from_secs(2)); // block for two seconds
	println!("{}", receiver.recv().unwrap()); // Received immediately
}

receiver.recv() is only called once, and then receiver is dropped. Once the receiver end is dropped (after the first call to recv) the senders will fail. In this case it's a race condition since the threads aren't joined in the main thread.

If the sleep is placed after the first recv, then the second send will probably be successful.

1 Like

tx, Join can be used as described but in my case threads never end. here is the fixed code in case anyone needed it

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

fn test(sender: Sender<&'static str>) {
	thread::spawn(move || {
		sender.send("level 2");
	});
}

fn main() {
	let (sender, receiver) = channel();
	let sender2 = sender.clone();
	thread::spawn(move || {
		sender2.send("level 1");
		test(sender2);
	});
	loop {
		thread::sleep(Duration::from_secs(2)); // block for two seconds
		println!("{}", receiver.recv().unwrap()); // Received immediately
	}
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.