Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 222
goo Avatar asked Feb 06 '23 08:02

goo


1 Answers

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")
    });
}

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");
}
like image 117
Shepmaster Avatar answered Feb 08 '23 14:02

Shepmaster