gpt4 book ai didi

rust - 线程中产生的循环不应该重复打印吗?

转载 作者:行者123 更新时间:2023-11-29 07:58:08 27 4
gpt4 key购买 nike

示例代码:

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 不应该在第一种情况下重复打印吗?

最佳答案

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

没有。 thread:spawn 的文档说(强调我的):

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.

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

在第二个示例中,您通过使主线程永远旋转来防止主线程退出。

What happens when you spawn a loop?

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


按照惯例,您不需要在 spawn 中使用额外的花括号,更标准的做法是只导入 std::thread 然后调用 线程::生成:

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

要让主线程等待子线程,您需要保留 JoinHandlethread::spawn 调用 join在上面:

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

handle.join().expect("The thread panicked");
}

关于rust - 线程中产生的循环不应该重复打印吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41597833/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com