Yilmaz
Yilmaz

Reputation: 49182

Why print statements inside rust `thread` do not run?

I am reading about concurrency in Rust so created a cargo lib to test the code. I wrote this basic function

use std::thread;

fn main() {
    thread::spawn( || {
        // I created 20 lines of print statements in thread, none prints out
        println!("Hello 1, world  thread!");
        println!("Hello 2, world  thread!");
        println!("Hello 3, world  thread!");
    });
    // also 20 lines here, they all executed
    println!("Hello 1, world main function!");
    println!("Hello 2, world main function!");
}

Code compiles, only print statements after the thread are logged on the terminal. I run cargo run many times but still same result.

to increase the chance to thread switching, inside the thread, I have 20 lines of print statements and I also put 20 lines of print statements outside the thread. But none of the print statements inside thread logs. I expected to see mixed logs from the spawn thread and the main thread.

I want to test out that when I have too many print statements, I will see some print out from the spawn thread and some from the main thread in mixed order. But I do not see any print out from spawn thread. I can use

use std::thread;
use std::time::Duration;
thread::sleep(Duration::from_millis(1));

or join.handle

but I do not understand why I do not see the expected behavior in the first place

I am using Kali Linux. I suspect that this might be related to my linux os but I could not find anything online related to this.

Upvotes: 0

Views: 1033

Answers (1)

Locke
Locke

Reputation: 8934

The program exits when the main thread ends. We can't say for sure which thread will exit first, but odds are it will be the thread that is already running. You can make the main thread wait for your other thread to finish by using the new thread's JoinHandle to wait until it finishes before exiting the program.

use std::thread;

fn main() {
    let join_handle = thread::spawn( || {
        println!("Hello 1, world  thread!");
        println!("Hello 2, world  thread!");
        println!("Hello 3, world  thread!");
    });
    println!("Hello 1, world main function!");
    println!("Hello 2, world main function!");
    
    // Wait until other thread has finished
    join_handle.join().expect("thread did not panic");
}

Rust Playground

Upvotes: 2

Related Questions