0
0
Rustprogramming~30 mins

Creating threads in Rust - Try It Yourself

Choose your learning style9 modes available
Creating threads
📖 Scenario: You are building a simple Rust program that uses threads to run tasks in parallel. This is useful when you want your program to do multiple things at the same time, like cooking and cleaning in a kitchen.
🎯 Goal: Create a Rust program that starts a new thread to print a message, while the main thread prints another message. This will show how threads work together.
📋 What You'll Learn
Create a new thread using std::thread::spawn
Use a closure to define the thread's task
Print a message from the new thread
Print a message from the main thread
Wait for the new thread to finish using join
💡 Why This Matters
🌍 Real World
Threads let programs do many things at once, like downloading files while showing a progress bar.
💼 Career
Understanding threads is important for building fast and responsive software in many jobs, including systems programming and web servers.
Progress0 / 4 steps
1
Create a new thread
Write code to create a new thread using std::thread::spawn that runs a closure printing "Hello from the new thread!". Store the thread handle in a variable called handle.
Rust
Hint

Use thread::spawn with a closure || { ... } to create the thread.

2
Print from the main thread
Add a line to print "Hello from the main thread!" in the main thread after creating the new thread.
Rust
Hint

Use println! to print the message in the main thread.

3
Wait for the new thread to finish
Call handle.join().unwrap() to wait for the new thread to finish before the program ends.
Rust
Hint

Use join() on the thread handle to wait for the thread to finish.

4
Print the final output
Run the program and print the output messages from both threads.
Rust
Hint

Run the program to see both messages printed. The order may vary because threads run in parallel.