线程中生成的循环不应该重复打印吗? [英] Shouldn't a loop spawned in a thread print repeatedly?

查看:42
本文介绍了线程中生成的循环不应该重复打印吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例代码:

fn main() {
    use std::thread::spawn;
    spawn(|| { loop { println!("a") } });
    // `a` is never printed
}

fn main() {
    use std::thread::spawn;
    spawn(|| { loop { println!("a") } });
    loop { }
    // `a` is printed repeatedly
}

a 在第二种情况下打印到标准输出,但在第一种情况下并非如此.这是为什么?a 不应该在第一种情况下也重复打印吗?

a prints to the standard output in the second case, but the same is not true in the first case. Why is that? Shouldn't a print repeatedly in the first case as well?

推荐答案

a 不应该在第一种情况下也重复打印吗?

Shouldn't a print repeatedly in the first case as well?

没有.thread:spawn 说(强调我的):

No. The documentation of thread:spawn says (emphasis mine):

加入句柄将在被删除时隐式分离子线程.在这种情况下,子线程可能比父线程存活时间更长(除非父线程是主线程;当主线程完成时整个进程终止.)此外,连接句柄提供了一个连接方法可以用来加入子线程.如果子线程发生恐慌,join 将返回一个包含给恐慌的参数的 Err.

The join handle will implicitly detach the child thread upon being dropped. In this case, the child thread may outlive the parent (unless the parent thread is the main thread; the whole process is terminated when the main thread finishes.) Additionally, the join handle provides a join method that can be used to join the child thread. If the child thread panics, join will return an Err containing the argument given to panic.

你的整个程序都退出了,因为主线程已经退出.子线程根本没有机会启动,更不用说打印任何东西了.

Your entire program exits because the main thread has exited. There was never even a chance for the child thread to start, much less print anything.

在第二个例子中,你通过导致主线程永远旋转来阻止主线程退出.

In the second example, you prevent the main thread from exiting by also causing that to spin forever.

当你产生一个循环时会发生什么?

What happens when you spawn a loop?

该线程将在循环中旋转,只要程序执行.

That thread will spin in the loop, as long as the program executes.

习惯上,spawn 中不需要额外的大括号,更标准的是只导入 std::thread 然后调用 thread::spawn:

Idiomatically, you don't need the extra curly braces in the spawn, and it's more standard to only import the std::thread and then call thread::spawn:

fn main() {
    use std::thread;
    thread::spawn(|| loop {
        println!("a")
    });
}

要让主线程等待子线程,您需要保留 JoinHandle 来自 thread::spawn 并调用 join 就可以了:

To have the main thread wait for the child, you need to keep the JoinHandle from thread::spawn and call join on it:

fn main() {
    use std::thread;
    let handle = thread::spawn(|| loop {
        println!("a")
    });
    
    handle.join().expect("The thread panicked");
}

这篇关于线程中生成的循环不应该重复打印吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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