How to create threads in Rust
Overview
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.
Syntax
thread::spawn(move || thread_func());
We used the thread::spawn function to create threads.
Parameters
- In the parameters, we'll use the
movekeyword to move the scope to the next thread. - We'll also call the
thread_func()function for the spawn thread implementation.
Example
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));}}
Explanation
- Lines 4–9: We declare a function with the name
thread_func, in which we print messages and add asleepfunction to make the thread sleep. - Line 13: We create a thread using
thread::spawn, also called thethread_func. - Lines 17–19: In the end, we print the main thread message
i, where we again used thesleepfunction to sleep thethreadfor 1 millisecond.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved