Rust Programming Language
Create Project
cargo new concurrency_example
cd concurrency_example
Edit main.rs
cd src
nano main.rs
enter this code:
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("Hi from the spawned thread: {}", i);
thread::sleep(Duration::from_millis(500));
}
});
for i in 1..5 {
println!("Hi from the main thread: {}", i);
thread::sleep(Duration::from_millis(1000));
}
handle.join().unwrap();
}
Explanation
Creating a Thread: thread::spawn creates a new thread.
Closure: The code inside || {...} is the thread’s task.
Main Thread: Continues to run its own loop.
Joining Threads: handle.join().unwrap() ensures the main thread waits for the spawned thread to finish.
Compile and run your program with Cargo:
cargo run
Output
You’ll see interleaved messages from both the main thread and the spawned thread, showing concurrent execution.
ben@HP-17:~/concurrency_example$ cargo run
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.07s
Running `target/debug/concurrency_example`
Hi from the main thread: 1
Hi from the spawned thread: 1
Hi from the spawned thread: 2
Hi from the main thread: 2
Hi from the spawned thread: 3
Hi from the spawned thread: 4
Hi from the main thread: 3
Hi from the spawned thread: 5
Hi from the spawned thread: 6
Hi from the main thread: 4
Hi from the spawned thread: 7
Hi from the spawned thread: 8
Hi from the spawned thread: 9
Ben Santora - October 2024
Top comments (0)