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?
No. From the documentation from
thread:spawn
, emphasis mine: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.
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 thestd::thread
and then callthread::spawn
: