Why does this line not print when the surrounding threads do print?

I'm an amateur programmer who mostly uses Python and I'm not especially advanced. Trying to pick up Rust for an ambitious project that's performance intensive. I've been playing around with threads trying to get to a state where I can have a "server" running and send simple commands to it. Some test code is below along with some sample output:

use std::{thread, time};
use std::sync::mpsc::channel;

fn main() {
    println!("Starting test...");
	
	let thread_server = thread::spawn(|| {
		counting_server();
	});
	let thread_test = thread::spawn(|| {
		loop {
			println!("Test");
			std::thread::sleep(time::Duration::from_secs(3));
		}
	});
	
	println!("Starting server...");
	thread_server.join().expect("Freak out.");
	println!("Server started");
	thread_test.join().expect("Freak out.");
	
	let mut input = String::new();
		
	while input != "quit" {
			std::io::stdin().read_line(&mut input).unwrap();
			println!("{0}", input);
	}
	
	println!("Done with all threads");
}

fn counting_server() {
	let mut i = 0;
	loop {
		i += 1;
		std::thread::sleep(time::Duration::from_secs(1));
	}
}

Output:

Starting test...
Starting server...
Test
Test
Test
Test
Test

What I don't understand is why the "Server started" line doesn't print even though the two lines on either side of it which spawn the threads do print. The execution clearly gets to the second thread, so did it just ignore that println?

Any help would be appreciated.

thread_server.join() won't return until the thread exits, which will never happen.

1 Like

The threads spawn when you call thread::spawn. They'll start running no matter what you do. The only thing join does is wait for the thread to finish, which never happens, so the main thread waits forever at the first join.

4 Likes

Ah! I get it now. Thanks!

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.