What happen after main thread is finish?

if main thread do not call join to wait for thread finish, will the thread be destructed suddenly?

In the following code, I comment out the join function, then not all the thread print out the line, will the function be called or not? What happen in this code?

use std::thread;

static NTHREADS: i32 = 10;

// This is the `main` thread
fn main() {
    // Make a vector to hold the children which are spawned.
    let mut children = vec![];

    for i in 0..NTHREADS {
        // Spin up another thread
        children.push(thread::spawn(move || {
            println!("this is thread number {}", i);
        }));
    }

    // for child in children {
    //     // Wait for the thread to finish. Returns a result.
    //     let _ = child.join();
    // }
}

link: https://doc.rust-lang.org/stable/rust-by-example/std_misc/threads.html

According to the library reference (https://doc.rust-lang.org/std/thread/)

When the main thread of a Rust program terminates, the entire program shuts down, even if other threads are still running.

This means that your program may stop before all the child threads have finished their work. In this case, printing a line to the terminal.

I assume this is done as part of the operating system’s process cleanup phase and there’s no real warning given to the child threads, but I’m not sure about that.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.