Rust Program: Create two Threads & Print "Hello, World!"
Rust Threads and Synchronization: Exercise-1 with Solution
Write a Rust program that creates two threads and prints "Hello, world!" from each thread.
Sample Solution:
Rust Code:
use std::thread; // Import the thread module from the standard library
fn main() {
// Define a closure to be executed by the first thread
let thread1 = thread::spawn(|| {
// Inside the closure, print "Hello, world!" for the first thread
println!("Rust Exercise! from thread 1!");
});
// Define a closure to be executed by the second thread
let thread2 = thread::spawn(|| {
// Inside the closure, print "Hello, world!" for the second thread
println!("Rust Exercise! from thread 2!");
});
// Wait for both threads to finish execution
thread1.join().unwrap();
thread2.join().unwrap();
}
Output:
Rust Exercise! from thread 1! Rust Exercise! from thread 2!
Explanation:
In the exercise above,
- First imort the "thread" module from the standard library, which provides functions and utilities for working with threads.
- Inside the "main()" function, we define two closures using the "||" syntax. These closures represent the code to be executed by each thread.
- We use the thread::spawn() function twice to create two separate threads. Each call to thread::spawn() takes a closure as an argument, and this closure represents the code to be executed by the thread.
- The closures passed to thread::spawn() each contain a println!() statement that prints "Hello, world!" along with an identifier for the respective thread.
- After spawning both threads, we use the "join()" method on each thread handle to wait for them to finish executing. This ensures that the program doesn't terminate before both threads have completed their execution.
- Finally, the program terminates, and "Hello, world!" is printed from both threads.
Rust Code Editor:
Previous: Rust Threads and Synchronization Exercises.
Next: Rust Program: Implement Producer-Consumer Pattern with Threads & Channels.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/rust/threads_and_synchronization/rust-threads-and-synchronization-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics