为什么这些线程在完成工作之前就退出了? [英] Why are these threads quitting before finishing their work?

查看:77
本文介绍了为什么这些线程在完成工作之前就退出了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

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的末尾添加一个延迟:

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

医生说这些线程的寿命应该比其父进程长,但在这里看来,它们一旦父进程(在本例中为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.

推荐答案

医生说这些线程的寿命应该比其父进程长,但在这里看来,它们一旦父进程(在本例中为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.

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

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

您要执行的操作是让主线程等待,直到其他线程结束,即您要将子线程联接"到主线程.为此,请参见 join 方法.

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

请注意,当JoinGuard掉落时,对join的调用是隐式的,但在此将其显式说明.

Note that the calls to join are implicit when the JoinGuard drops, but they're made explicit here for illustration.

这篇关于为什么这些线程在完成工作之前就退出了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆