Reading file from thread has undefined behavior

I'm trying to read a file from a newly spawned thread as follows:

use std::fs;
use std::thread;

fn main() {
    thread::spawn(|| {
        println!("Thread spawned");

        let bytes = fs::read(&"./.gitignore").unwrap();

        println!("Bytes: {:?}", bytes);
    });
}

What happens is nothing is printed to console, other than default cargo run output:

➜  minimal-error git:(master) βœ— cargo run
   Compiling minimal-error v0.1.0 (.../minimal-error)
    Finished dev [unoptimized + debuginfo] target(s) in 0.23s
     Running `target/debug/minimal-error`

If thread is removed, the file can be read successfully:

use std::fs;
use std::thread;

fn main() {
        let bytes = fs::read(&"./.gitignore").unwrap();
        println!("Bytes: {:?}", bytes);
}
➜  minimal-error git:(master) βœ— cargo run
   Compiling minimal-error v0.1.0 (.../minimal-error)
    Finished dev [unoptimized + debuginfo] target(s) in 0.19s
     Running `target/debug/minimal-error`
Bytes: [47, 116, 97, 114, 103, 101, 116, 10]

Am I missing something about reading files from threads?

It's because the main thread is terminated before anything happens in the child thread.

https://doc.rust-lang.org/std/thread/index.html

When the main thread of a Rust program terminates, the entire program shuts down, even if other threads are still running. However, this module provides convenient facilities for automatically waiting for the termination of a child thread (i.e., join).

3 Likes