Why do these threads stop working before shutting down?

Given the following code:

use std::sync::mpsc::{channel, Sender, Receiver}; use std::thread; fn transceiver( tx: Sender<u32>, tx_string: &str, rx: Receiver<u32>, rx_string: &str, ) { let message_count = 3; for message in 0..message_count { println!("message {}: {}", message, tx_string); tx.send(message).unwrap(); println!("message {}: {}", rx.recv().unwrap(), rx_string); } } fn main() { let (atx, arx) = channel(); let (btx, brx) = channel(); thread::spawn(move || { transceiver(atx, "A --> B", brx, "A <-- B"); }); thread::spawn(move || { transceiver(btx, "B --> A", arx, "B <-- A"); }); } 

I have no conclusion. I had to add a delay at the end of main :

 std::old_io::timer::sleep(std::time::duration::Duration::seconds(1)); 

After that, I get this output:

 message 0: B --> A message 0: A --> B message 0: A <-- B message 0: B <-- A message 1: B --> A message 1: A --> B message 1: A <-- B message 2: A --> B message 1: B <-- A message 2: B --> A message 2: B <-- A message 2: A <-- B 

Doc says that these threads should outlive their parents, but they seem to die as soon as the parent (in this case, main ) dies.

0
source share
1 answer

Doc says that these streams should outlive their parents, but here it seems that they die as soon as the parent (in this case main ) dies.

This does not apply to the main thread; the program ends after the main thread completes.

What you want to do is that the main thread will wait for the rest of the threads to finish, i.e. you want to "attach" the child thread to the main thread. See join for this.

 let (atx, arx) = channel(); let (btx, brx) = channel(); let guard0 = thread::scoped(move || { transceiver(atx, "A --> B", brx, "A <-- B"); }); let guard1 = thread::scoped(move || { transceiver(btx, "B --> A", arx, "B <-- A"); }); guard0.join(); guard1.join(); 

Note that join calls are implicit when JoinGuard crashes, but they are provided here for illustration.

+4
source

Source: https://habr.com/ru/post/980605/


All Articles