This uses the
first_threadcode, incode/02_threads.
Looking back at the workspaces class from last week, it's a great idea to have a workspace. Let's create one:
cargo new LiveWeek2Now edit Cargo.toml to include a workspace:
[workspace]
members = []Now change directory to the LiveWeek2 directory and create a new project named FirstThread:
cd LiveWeek2
cargo new FirstThreadAnd add the project to the workspace:
[workspace]
members = [
"FirstThread"
]In main.rs, replace the contents with the following:
fn hello_thread() {
println!("Hello from thread!");
}
fn main() {
println!("Hello from main thread!");
let thread_handle = std::thread::spawn(hello_thread);
thread_handle.join().unwrap();
}Now run the program:
Hello from main thread!
Hello from thread!So what's going on here? Let's break it down:
- The program starts in the main thread.
- The main thread prints a message.
- We create a thread using
std::thread::spawnand tell it to run the functionhello_thread. - The return value is a "thread handle". You can use these to "join" threads---wait for them to finish.
- We call
joinon the thread handle, which waits for the thread to finish.
Run the program a few times. Sometimes the secondary thread finishes, sometimes it doesn't. Threads don't outlive the main program, so if the main program exits before the thread finishes, the thread is killed.