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

  1. In the parameters, we'll use the move keyword to move the scope to the next thread.
  2. We'll also call the thread_func() function for the spawn thread implementation.

Example

use std::thread;
use std::time::Duration;
// Thread function
fn thread_func() {
for i in 1..8 {
println!(" {} spawned thread! ", i);
thread::sleep(Duration::from_millis(1));
}
}
fn main() {
// Thread
thread::spawn(move || thread_func());
//main function
for 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 a sleep function to make the thread sleep.
  • Line 13: We create a thread using thread::spawn, also called the thread_func.
  • Lines 17–19: In the end, we print the main thread message i, where we again used the sleep function to sleep the thread for 1 millisecond.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved