Let’s Learn Rust 007: Threads and Concurrency in Rust
Before We Start
If you have been following along, we have covered the core of Rust: ownership, structs, enums, traits, error handling, and even built a real CLI app. Now we go one level deeper.
Concurrency.
I will be honest, this is the topic I was most curious about when I started learning Rust. I had written concurrent code in Python and Java before, and both times I ran into race conditions that took way too long to debug. So when I heard Rust handles concurrency at compile time, I had to see it for myself.
This is where a lot of languages start showing cracks. Race conditions. Deadlocks. Data getting corrupted because two threads touched the same variable at the same time. These bugs are brutal. They are hard to reproduce, hard to debug, and they show up in production at the worst possible time.
Rust handles this differently. The same ownership system that protects your memory also protects your data across threads, and it does it at compile time. The compiler catches the bugs before your program ever runs. Coming from Python where the GIL quietly limits your parallelism, or Java where you pray you remembered to synchronize everything correctly, this felt like a completely different level of confidence.
That is the big idea. Let’s see how it works.
1. What Is a Thread?
When your program starts, it runs on a single thread. One sequence of instructions, one at a time. A thread is basically a unit of execution.
Spawning a new thread means your program can now run two things at the same time. While one thread is reading a file, another is processing data. Both happening simultaneously.
In Python, the Global Interpreter Lock (GIL) means threads can exist but true parallel execution of Python code is blocked. In Java you have Thread and Runnable but the language gives you no compile-time safety around what data those threads can touch. In C++ you have std::thread which is powerful but gives you a loaded gun with no safety.
In Rust, you create a thread using std::thread::spawn:
use std::thread;
fn main() {
let handle = thread::spawn(|| {
println!("Hello from a new thread!");
});
println!("Hello from the main thread!");
handle.join().unwrap(); // Wait for the thread to finish
}
use std::thread;
fn main() {
let handle = thread::spawn(|| {
println!("Hello from a new thread!");
});
println!("Hello from the main thread!");
handle.join().unwrap(); // Wait for the thread to finish
}
A few things to notice here:
thread::spawntakes a closure (the || syntax). Whatever is inside runs in the new thread.handle.join()tells the main thread to wait. Without it, the main thread might finish and kill the whole program before the spawned thread gets to run..unwrap()becausejoin()returns aResult. If the thread panicked, you get anErr.
2. Moving Data Into Threads
Here is something that trips people up early. I got hit by this on my first attempt. Try this:
use std::thread;
fn main() {
let message = String::from("Hello!");
let handle = thread::spawn(|| {
println!("{}", message); // ERROR
});
handle.join().unwrap();
}
use std::thread;
fn main() {
let message = String::from("Hello!");
let handle = thread::spawn(|| {
println!("{}", message); // ERROR
});
handle.join().unwrap();
}
The compiler complains. Why? Because message lives in the main thread. The closure borrows it, but Rust has no guarantee that message will still be alive for the entire duration of the spawned thread. The main thread could drop it first.
In Python you would just reference the variable and it would work, until it does not and you spend an hour figuring out why your data looks corrupted. In C++ you can pass by reference into a thread and the compiler says nothing, even if that reference goes dangling.
Rust says no at compile time. The fix is move. It transfers ownership of message into the closure:
use std::thread;
fn main() {
let message = String::from("Hello!");
let handle = thread::spawn(move || {
println!("{}", message); // Works
});
handle.join().unwrap();
}
use std::thread;
fn main() {
let message = String::from("Hello!");
let handle = thread::spawn(move || {
println!("{}", message); // Works
});
handle.join().unwrap();
}
Now the thread owns message. The main thread can no longer use it. Clean, explicit, and safe.
3. Spawning Multiple Threads
Let’s combine this with a loop:
use std::thread;
fn main() {
let mut handles = vec![];
for i in 0..5 {
let handle = thread::spawn(move || {
println!("Thread {} is running", i);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
}
use std::thread;
fn main() {
let mut handles = vec![];
for i in 0..5 {
let handle = thread::spawn(move || {
println!("Thread {} is running", i);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
}
Five threads running at the same time. The order of the printed output will vary each time you run it. That is the nature of concurrency and it is expected behaviour, not a bug.
4. Sharing Data Between Threads
This is where it gets interesting. What if two threads both need to read and write the same data?
In Java you would reach for synchronized or volatile. In C++ you would grab a std::mutex and manually lock and unlock, hoping you do not forget the unlock. In Python you would use threading.Lock(). All of these work, but they rely on you getting it right every time. Miss one lock and you have a race condition.
In Rust, the compiler stops you before you even try:
use std::thread;
fn main() {
let mut counter = 0;
let handle = thread::spawn(|| {
counter += 1; // ERROR: cannot borrow `counter` as mutable
});
handle.join().unwrap();
}
use std::thread;
fn main() {
let mut counter = 0;
let handle = thread::spawn(|| {
counter += 1; // ERROR: cannot borrow `counter` as mutable
});
handle.join().unwrap();
}
Two ownership rules are clashing here. Rust has a solution for exactly this.
5. Arc and Mutex: The Standard Solution
To safely share data across threads, Rust gives you two types that work together:
Mutex<T>does Mutual Exclusion. Only one thread can access the data at a time. Everyone else waits.Arc<T>is Atomic Reference Counted. LikeRc<T>but safe to use across threads. It lets multiple threads share ownership of the same value.
When I first saw Arc::new(Mutex::new(0)) I thought it looked unnecessarily complicated. Coming from Java where you just write synchronized(this) and move on, this felt verbose. But once I understood what each layer was doing, it started making complete sense. You are being explicit about every guarantee you want. Together they look like this:
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); // Clone the Arc, not the data
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap(); // Acquire the lock
*num += 1;
}); // Lock is automatically released when `num` goes out of scope
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Final counter value: {}", *counter.lock().unwrap()); // 5
}
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); // Clone the Arc, not the data
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap(); // Acquire the lock
*num += 1;
}); // Lock is automatically released when `num` goes out of scope
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Final counter value: {}", *counter.lock().unwrap()); // 5
}
Step by step:
Arc::new(Mutex::new(0))wraps the data in aMutex, then wraps that in anArc.Arc::clone(&counter)creates a new pointer to the same data. Each thread gets its own pointer, all pointing at one thing.counter.lock().unwrap()acquires the lock. If another thread already has it, this blocks until it gets released.- When
numgoes out of scope at the end of the closure, the lock releases automatically. No forgetting to unlock, which in C++ is a real and painful problem.
6. Message Passing with Channels
Shared memory is one way to communicate between threads. Rust also gives you channels. Think of them as pipes. One thread sends a value, another thread receives it.
Go developers will feel familiar here. Go’s whole philosophy is built around channels. Rust borrowed the idea and it works just as well. The difference is Rust gives you both options, shared state with Mutex or message passing with channels, and lets you pick what fits.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel(); // tx = transmitter, rx = receiver
thread::spawn(move || {
let message = String::from("Hello from the thread");
tx.send(message).unwrap();
});
let received = rx.recv().unwrap(); // Block and wait for a message
println!("Got: {}", received);
}
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel(); // tx = transmitter, rx = receiver
thread::spawn(move || {
let message = String::from("Hello from the thread");
tx.send(message).unwrap();
});
let received = rx.recv().unwrap(); // Block and wait for a message
println!("Got: {}", received);
}
mpsc stands for multiple producer, single consumer. You can have many senders, one receiver.
Sending multiple values works the same way:
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let messages = vec!["one", "two", "three"];
for msg in messages {
tx.send(msg).unwrap();
thread::sleep(Duration::from_millis(100));
}
});
for received in rx { // rx acts as an iterator
println!("Got: {}", received);
}
}
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let messages = vec!["one", "two", "three"];
for msg in messages {
tx.send(msg).unwrap();
thread::sleep(Duration::from_millis(100));
}
});
for received in rx { // rx acts as an iterator
println!("Got: {}", received);
}
}
When all the senders are dropped, the receiver’s iterator ends on its own.
7. Send and Sync Traits
Arc and Mutex handle thread safety automatically. Rust enforces this through two marker traits:
Sendmeans a type is safe to send to another thread.Syncmeans a type is safe to share between threads, so a&TisSend.
Most standard types implement these automatically. Rc<T> is the classic exception. It does reference counting without atomic operations, so sharing it across threads would corrupt the count. The compiler blocks you from doing it.
This is the thing that really separates Rust from Java or C++. In those languages, nothing stops you from sharing an Rc-equivalent across threads at runtime. You only find out something went wrong when production breaks. In Rust, the compiler knows the types are unsafe to send and simply does not allow it.
You will almost never implement Send or Sync manually. Knowing they exist helps you understand why certain things compile and others do not.
8. A Practical Example: Parallel Task Processing
Let’s put it all together with something real:
String {
format!("Processed: {}", task.to_uppercase())
}
fn main() {
let tasks = vec!["task_a", "task_b", "task_c", "task_d", "task_e"];
let results = Arc::new(Mutex::new(vec![]));
let mut handles = vec![];
for task in tasks {
let results = Arc::clone(&results);
let handle = thread::spawn(move || {
let result = process_task(task);
results.lock().unwrap().push(result);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
let final_results = results.lock().unwrap();
for r in final_results.iter() {
println!("{}", r);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::sync::{Arc, Mutex};
use std::thread;
fn process_task(task: &str) -> String {
format!("Processed: {}", task.to_uppercase())
}
fn main() {
let tasks = vec!["task_a", "task_b", "task_c", "task_d", "task_e"];
let results = Arc::new(Mutex::new(vec![]));
let mut handles = vec![];
for task in tasks {
let results = Arc::clone(&results);
let handle = thread::spawn(move || {
let result = process_task(task);
results.lock().unwrap().push(result);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
let final_results = results.lock().unwrap();
for r in final_results.iter() {
println!("{}", r);
}
}
use std::sync::{Arc, Mutex};
use std::thread;
fn process_task(task: &str) -> String {
format!("Processed: {}", task.to_uppercase())
}
fn main() {
let tasks = vec!["task_a", "task_b", "task_c", "task_d", "task_e"];
let results = Arc::new(Mutex::new(vec![]));
let mut handles = vec![];
for task in tasks {
let results = Arc::clone(&results);
let handle = thread::spawn(move || {
let result = process_task(task);
results.lock().unwrap().push(result);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
let final_results = results.lock().unwrap();
for r in final_results.iter() {
println!("{}", r);
}
}
Five tasks, five threads, results collected safely into a shared Vec. The order in the Vec depends on which thread finishes first, but there are zero race conditions, zero corruption, zero undefined behavior. In Python this kind of parallel processing usually means reaching for multiprocessing instead of threads just to get around the GIL. In Rust, threads do real parallel work out of the box.
9. Deadlocks: What Rust Cannot Catch
Rust prevents data races. It does not prevent deadlocks.
A deadlock happens when two threads are each waiting for a lock the other one holds. Both block forever. This can happen in any language and Rust is not an exception.
// Thread 1 holds Lock A, waiting for Lock B
// Thread 2 holds Lock B, waiting for Lock A
// Neither ever proceeds
// Thread 1 holds Lock A, waiting for Lock B
// Thread 2 holds Lock B, waiting for Lock A
// Neither ever proceeds
The fix is discipline. Always acquire locks in the same order across all threads, and hold locks for as short a time as possible. This is true in Java, C++, Python, and Rust equally.
Summary
Here is what you can do now:
thread::spawnto create threads,jointo wait for themmoveclosures to transfer ownership into a threadArc<Mutex<T>>to safely share mutable data across threadsmpsc::channelfor thread-to-thread communicationSendandSyncas the foundation Rust builds on under the hood
Concurrency in Rust is more verbose than Python or Java. That verbosity is the trade-off for correctness. You are writing down every guarantee explicitly and the compiler holds you to it. Once it clicked for me I stopped seeing the verbosity as a problem and started seeing it as documentation that the compiler verifies.
What’s Next
In the next article we go into Rust’s async story. async/await and the tokio runtime. That is where Rust’s concurrency really shines for I/O-heavy work like web servers and network applications.
Happy coding and safe assembling!
Follow this series and join us in mastering Rust from scratch!


