Shouldn't a loop spawned in a thread print rep

2020-04-10 02:17发布

Example code:

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 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?

标签: rust
1条回答
Explosion°爆炸
2楼-- · 2020-04-10 02:48

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

No. From the documentation from thread:spawn, emphasis mine:

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.


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") });
}
查看更多
登录 后发表回答