Shouldn't a loop spawned in a thread print repeatedly?

后端 未结 1 1314
鱼传尺愫
鱼传尺愫 2021-01-21 04:46

Example code:

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


        
相关标签:
1条回答
  • 2021-01-21 04:55

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

    No. The documentation of thread:spawn says (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") });
    }
    
    0 讨论(0)
提交回复
热议问题