Why are these threads quitting before finishing th

2019-09-04 03:04发布

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 get no output. 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

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

1条回答
Fickle 薄情
2楼-- · 2019-09-04 04:03

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

This does not apply to the main thread; the program ends once the main thread is finished.

What you want to do is have the main thread wait until the other threads finish, i.e. you want to "join" the child thread to the main thread. See the join method 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 the calls to join are implicit when the JoinGuard drops, but they're made explicit here for illustration.

查看更多
登录 后发表回答