Rust
December 2, 2026 8 min read

Concurrency and Multithreading in Rust

HS
HEMANT SINGH
Technical Writer & Educator

1. What Is Concurrency?

Concurrency means managing multiple tasks during overlapping periods of time.

A program may work on one task, switch to another, and continue making progress on both.

For example:

  1. Task 1: Download student data.
  2. Task 2: Calculate student fees.
  3. Task 3: Generate a report.

Concurrency helps applications manage multiple activities efficiently.

2. What Is Multithreading?

A thread is an independent sequence of execution inside a program.

Multithreading means running multiple threads within the same application.

For example, a program can use:

  1. Main thread
  2. Download thread
  3. Processing thread
  4. Reporting thread

Each thread can execute its own work.

3. Creating a Thread Using thread::spawn()

Rust provides thread::spawn() to create a new thread.

Syntax:

thread::spawn(|| {
// Code executed by the new thread
});

Example:

use std::thread;

fn main() {
thread::spawn(|| {
println!("Hello from another thread!");
});

println!("Hello from main thread!");
}

The output order is not guaranteed.

The new thread may not finish before the main thread exits. When the main thread finishes, the process can terminate even if another thread is still running.

We will solve this using join().

4. Understanding join()

The join() method waits for a thread to finish.

It returns a Result, which indicates whether the thread completed successfully or panicked.

Example:

use std::thread;

fn main() {
let handle = thread::spawn(|| {
println!("Child thread is running");
});

println!("Main thread is running");

handle.join().unwrap();

println!("Child thread finished");
}

Possible Output:

Main thread is running
Child thread is running
Child thread finished

The first two messages may appear in either order.

However, Child thread finished appears after the child thread has completed.

Explanation:

  1. thread::spawn() creates a new thread.
  2. handle stores the thread's join handle.
  3. join() waits for the thread to finish.
  4. unwrap() panics if the child thread panicked.

5. Running Multiple Threads

You can create multiple threads in one program.

Example:

use std::thread;

fn main() {
let thread1 = thread::spawn(|| {
println!("Thread 1 is running");
});

let thread2 = thread::spawn(|| {
println!("Thread 2 is running");
});

thread1.join().unwrap();
thread2.join().unwrap();

println!("All threads completed");
}

Possible Output:

Thread 1 is running
Thread 2 is running
All threads completed

The first two messages can appear in either order.

6. Using move with Threads

Sometimes a thread needs to access variables created in the main thread.

Rust uses ownership rules to ensure that references remain valid.

The move keyword transfers ownership of captured values into the closure.

Example:

use std::thread;

fn main() {
let name = String::from("Hemant");

let handle = thread::spawn(move || {
println!("Hello, {}", name);
});

handle.join().unwrap();
}

Output:

Hello, Hemant

Here:

  1. name is created in the main thread.
  2. move transfers ownership of the String into the thread closure.
  3. The new thread can safely use the String.

After moving name, the main thread cannot use that original variable.

7. Understanding thread::sleep()

The sleep() function pauses a thread for a specified duration.

Example:

use std::thread;
use std::time::Duration;

fn main() {
let handle = thread::spawn(|| {
for i in 1..=3 {
println!("Child: {}", i);

thread::sleep(Duration::from_secs(1));
}
});

for i in 1..=3 {
println!("Main: {}", i);

thread::sleep(Duration::from_secs(1));
}

handle.join().unwrap();
}

Possible Output:

Main: 1
Child: 1
Main: 2
Child: 2
Main: 3
Child: 3

The exact order may vary.

Duration::from_secs(1) represents one second.

8. Understanding Message Passing

Message passing allows threads to communicate by sending data to each other.

Rust provides channels for this purpose.

A channel has two main parts:

  1. Sender: Sends data.
  2. Receiver: Receives data.

Rust provides the mpsc module for multiple-producer, single-consumer channels.

Import it using:

use std::sync::mpsc;

9. Creating a Channel

Example:

use std::sync::mpsc;
use std::thread;

fn main() {
let (sender, receiver) = mpsc::channel();

thread::spawn(move || {
sender.send("Hello from child thread").unwrap();
});

let message = receiver.recv().unwrap();

println!("{}", message);
}

Output:

Hello from child thread

Explanation:

  1. mpsc::channel() creates a channel.
  2. sender sends data.
  3. receiver receives data.
  4. send() sends a message.
  5. recv() waits until a message is received.

10. Sending Multiple Messages

You can send multiple messages through the same channel.

Example:

use std::sync::mpsc;
use std::thread;

fn main() {
let (sender, receiver) = mpsc::channel();

thread::spawn(move || {
let messages = vec![
"Student registered",
"Fee payment received",
"Report generated",
];

for message in messages {
sender.send(message).unwrap();
}
});

for received in receiver {
println!("{}", received);
}
}

Output:

Student registered
Fee payment received
Report generated

The receiver iterates over incoming messages until all sender instances are dropped and the channel is closed.

11. Sending Data Between Threads

Channels can also send numbers and other owned data types.

Example:

use std::sync::mpsc;
use std::thread;

fn main() {
let (sender, receiver) = mpsc::channel();

thread::spawn(move || {
let total = 100 + 200;

sender.send(total).unwrap();
});

let result = receiver.recv().unwrap();

println!("Total: {}", result);
}

Output:

Total: 300

Here, the child thread calculates the result and sends it to the main thread.

12. Sharing Data Between Threads Using Arc

Sometimes multiple threads need access to the same data.

Rust provides Arc<T> for shared ownership across threads.

Example:

use std::sync::Arc;
use std::thread;

fn main() {
let number = Arc::new(100);

let number_clone = Arc::clone(&number);

let handle = thread::spawn(move || {
println!("Child: {}", number_clone);
});

println!("Main: {}", number);

handle.join().unwrap();
}

Possible Output:

Main: 100
Child: 100

Both threads can access the same underlying value.

However, Arc<T> alone does not allow arbitrary mutation of the shared value.

For shared mutation, we need another tool such as Mutex<T>.

13. Shared Mutable Data Using Arc and Mutex

A Mutex<T> protects data so that only one thread can access it mutably at a time.

When combined with Arc<T>, it allows multiple threads to share and safely modify the same data.

Example:

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
let counter = Arc::new(Mutex::new(0));

let mut handles = vec![];

for _ in 0..5 {
let counter = Arc::clone(&counter);

let handle = thread::spawn(move || {
let mut value = counter.lock().unwrap();

*value += 1;
});

handles.push(handle);
}

for handle in handles {
handle.join().unwrap();
}

println!("Counter: {}", *counter.lock().unwrap());
}

Output:

Counter: 5

Explanation:

  1. Arc allows all threads to share ownership.
  2. Mutex protects the counter.
  3. lock() obtains exclusive access.
  4. *value += 1 increases the counter.
  5. join() waits for all threads.
  6. The final counter value is printed.

14. Understanding Race Conditions

A race condition occurs when multiple threads access shared data and the final result depends on the timing or order of their operations.

For example, suppose two threads try to update the same counter simultaneously.

Without proper synchronization, their operations could interfere with each other.

Rust's ownership and type systems prevent many unsafe data races.

Mutex<T> is one way to protect shared mutable data.

15. Understanding Scoped Threads

Sometimes you want to create threads that borrow local variables without moving ownership into each thread.

Rust provides scoped threads through thread::scope().

Scoped threads are guaranteed to finish before the scope ends.

Example:

use std::thread;

fn main() {
let numbers = vec![10, 20, 30];

thread::scope(|scope| {
scope.spawn(|| {
println!("Thread: {:?}", numbers);
});

println!("Main: {:?}", numbers);
});

println!("After threads: {:?}", numbers);
}

Possible Output:

Main: [10, 20, 30]
Thread: [10, 20, 30]
After threads: [10, 20, 30]

The first two messages may appear in either order.

The important point is that numbers remains valid throughout the scope, and the scoped thread finishes before the scope ends.

16. Difference Between Concurrency and Parallelism

These terms are related but have different meanings.


Concurrency

Parallelism

Multiple tasks make progress during overlapping periods

Multiple tasks execute at the same time

Tasks may take turns

Tasks run simultaneously

Can happen on one CPU core

Requires multiple execution resources

Focuses on managing multiple tasks

Focuses on executing tasks simultaneously

A multithreaded program can use concurrency without necessarily achieving parallel execution.

17. Common Mistakes


Mistake

Explanation

Forgetting join()

The main thread may finish before the child thread

Sharing local references incorrectly

The reference may not live long enough

Forgetting move

A spawned thread may not be allowed to capture a borrowed local value

Using Rc across threads

Rc is not thread-safe

Modifying shared data without synchronization

Can cause data races in systems that permit it

Holding a Mutex lock too long

Can block other threads

Calling recv() when no sender remains

It returns an error when the channel is disconnected

18. Practice Exercises

Exercise 1:

Create a new thread using thread::spawn().

Print:

Hello from Rust thread

Exercise 2:

Create two threads.

  1. Thread 1 prints numbers from 1 to 5.
  2. Thread 2 prints numbers from 6 to 10.

Wait for both threads using join().

Exercise 3:

Create a channel and send a message from a child thread to the main thread.

Exercise 4:

Create an Arc containing a string and share it with two threads.

Exercise 5:

Create an Arc<Mutex<i32>> counter.

Start five threads and make each thread increase the counter by 10.

The expected final value is 50.

19. Mini Project: Multi-Threaded Student Fee Calculator

Create a program that calculates fees for multiple students using separate threads.

Requirements

  1. Create a vector containing student fee amounts.
  2. Start a separate thread to calculate the total fees.
  3. Start another thread to calculate the average fee.
  4. Use join() to collect both results.
  5. Display the total and average.

Complete Code

use std::thread;

fn main() {
let fees = vec![300, 500, 400, 600, 200];

let fees_for_total = fees.clone();

let total_handle = thread::spawn(move || {
fees_for_total.iter().sum::<i32>()
});

let fees_for_average = fees.clone();

let average_handle = thread::spawn(move || {
let total: i32 = fees_for_average.iter().sum();

total as f64 / fees_for_average.len() as f64
});

let total = total_handle.join().unwrap();

let average = average_handle.join().unwrap();

println!("Total Fees: {}", total);

println!("Average Fees: {:.2}", average);
}

Expected Output

Total Fees: 2000
Average Fees: 400.00