In most modern systems, the operating system maintains numerous processes simultaneously. You can also have independent components that operate concurrently within your program.
Threads are the features that run these independent components in parallel. Interestingly for Rust programmers, one of the language’s primary aims is to make concurrent programming safe and efficient. Many of these bugs are impossible to write in Rust. Incorrect code will refuse to build and display an error message detailing the issue. So, in Rust, we can make our code run parallel by using threads for better understanding. Let's explore how it works in Rust.
thread::spawn(move || thread_func());
We used the thread::spawn
function to create threads.
move
keyword to move the scope to the next thread. thread_func()
function for the spawn thread implementation. use std::thread;use std::time::Duration;// Thread functionfn thread_func() {for i in 1..8 {println!(" {} spawned thread! ", i);thread::sleep(Duration::from_millis(1));}}fn main() {// Threadthread::spawn(move || thread_func());//main functionfor i in 1..5 {println!(" {} number main thread!", i);thread::sleep(Duration::from_millis(1));}}
thread_func
, in which we print messages and add a sleep
function to make the thread sleep.thread::spawn
, also called the thread_func
.i
, where we again used the sleep
function to sleep the thread
for 1 millisecond.Free Resources