为什么这些线程在完成工作之前退出?

Why are these threads quitting before finishing their work?

给定以下代码:

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");
    });
}

我没有输出。我不得不在 main:

末尾添加延迟
std::old_io::timer::sleep(std::time::duration::Duration::seconds(1));

之后,我得到这个输出:

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

文档说这些线程应该比它们的父线程长寿,但在这里它们似乎会在父线程(在本例中为 main)死亡后立即死亡。

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.

这不适用于主线程;主线程完成后程序结束。

你想要做的是让主线程等到其他线程完成,即你想 "join" 子线程到主线程。请参阅 join 方法。

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();

请注意,当 JoinGuard 下降时,对 join 的调用是隐式的,但为了说明,它们在这里是显式的。