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:
- Task 1: Download student data.
- Task 2: Calculate student fees.
- 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:
- Main thread
- Download thread
- Processing thread
- 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:
Example:
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:
Possible Output:
The first two messages may appear in either order.
However, Child thread finished appears after the child thread has completed.
Explanation:
thread::spawn()creates a new thread.handlestores the thread's join handle.join()waits for the thread to finish.unwrap()panics if the child thread panicked.
5. Running Multiple Threads
You can create multiple threads in one program.
Example:
Possible Output:
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:
Output:
Here:
nameis created in the main thread.movetransfers ownership of the String into the thread closure.- 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:
Possible Output:
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:
- Sender: Sends data.
- Receiver: Receives data.
Rust provides the mpsc module for multiple-producer, single-consumer channels.
Import it using:
9. Creating a Channel
Example:
Output:
Explanation:
mpsc::channel()creates a channel.sendersends data.receiverreceives data.send()sends a message.recv()waits until a message is received.
10. Sending Multiple Messages
You can send multiple messages through the same channel.
Example:
Output:
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:
Output:
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:
Possible Output:
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:
Output:
Explanation:
Arcallows all threads to share ownership.Mutexprotects the counter.lock()obtains exclusive access.*value += 1increases the counter.join()waits for all threads.- 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:
Possible Output:
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 | The main thread may finish before the child thread |
Sharing local references incorrectly | The reference may not live long enough |
Forgetting | A spawned thread may not be allowed to capture a borrowed local value |
Using |
|
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 | It returns an error when the channel is disconnected |
18. Practice Exercises
Exercise 1:
Create a new thread using thread::spawn().
Print:
Exercise 2:
Create two threads.
- Thread 1 prints numbers from 1 to 5.
- 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
- Create a vector containing student fee amounts.
- Start a separate thread to calculate the total fees.
- Start another thread to calculate the average fee.
- Use
join()to collect both results. - Display the total and average.