Concurrency: Multithreading Basics
7 min read
1. Introduction to Multithreading with std::thread
The Problem: The Single-Track Mind 🧠
By default, C++ programs constitute a single sequence of execution. Your code runs line by line, top to bottom.
Imagine a pizzeria with only one chef. This chef has to take the order, knead the dough, chop the toppings, bake the pizza, and deliver it. While they are driving the delivery scooter, nobody is making pizza. The kitchen sits empty. This is Serial Execution. It is safe, predictable, and horribly inefficient for complex tasks.
In computing, modern CPUs have multiple cores (multiple brains). If you write a single-threaded program, you are using one brain and letting the other 7 (or 15, or 31) play Solitaire.
The Solution: Multithreading 🧵
Multithreading allows a program to execute multiple sequences of instructions simultaneously.
In C++11 and later, the standard library provides std::thread to create and manage these parallel execution paths.
Technical Definition: A thread is a lightweight process that executes an independent sequence of instructions while sharing the same memory space as the main program.
Hello, Thread!
Let's fire the single chef and hire a team.
To use threads, you must include the <thread> header.
#include <iostream>
#include <thread> // Required for std::thread
// This is the function the thread will execute
void makePizza() {
std::cout << "Chef is making pizza on a separate thread! ID: "
<< std::this_thread::get_id() << std::endl;
}
int main() {
std::cout << "Main: Taking orders. ID: " << std::this_thread::get_id() << std::endl;
// 1. Create a thread
// The moment this line executes, 'makePizza' starts running
std::thread chefThread(makePizza);
// 2. Do other work in the main thread
std::cout << "Main: Scrubbing the floors while chef cooks." << std::endl;
// 3. WAIT for the thread to finish (Critical Step!)
chefThread.join();
std::cout << "Main: Pizza is ready and shop is closing." << std::endl;
return 0;
}Did you know? 🤯
The Operating System is the ultimate micromanager. It switches between threads so fast (context switching) that it looks like they are running at the exact same nanosecond, even if you only have one CPU core. On multi-core systems, they actually are running at the same time.
2. Passing Arguments and Joining Threads
The Problem: Ghost Threads and Arguments
Two immediate problems arise when you spawn a thread:
- Arguments: Functions usually need input. How do you pass data to a function running in a parallel dimension?
- Lifecycle: If
main()finishes and returns0while your thread is still running, the program terminates. The thread gets killed instantly (like turning off the TV while a movie is playing). This causes a crash (specifically,std::terminateis called).
The Solution: Constructor Params and join()
Passing Arguments
You pass arguments to the thread simply by adding them to the std::thread constructor after the function name.
The join() Standard
Calling .join() pauses the current thread (usually Main) until the created thread finishes execution. It synchronizes them.
Industry Standard: Always decide immediately if a thread should be join() (waited for) or detach() (run freely in the background). 95% of the time in application development, you want join(). Detached threads are difficult to debug and manage.
Practical Example
#include <iostream>
#include <thread>
#include <string>
void downloadFile(std::string fileName, int speed) {
std::cout << "Downloading " << fileName << " at " << speed << " MB/s..." << std::endl;
// Simulate work
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Finished " << fileName << "!" << std::endl;
}
int main() {
std::string file = "doom_eternal.exe";
int speed = 50;
// Pass arguments directly: function, arg1, arg2
std::thread downloader(downloadFile, file, speed);
std::cout << "Main: While that downloads, I'll make coffee." << std::endl;
// If we forget this, the program crashes when main exits!
if (downloader.joinable()) {
downloader.join();
}
std::cout << "Main: Coffee done, download done." << std::endl;
return 0;
}⚠️ The Reference Trap
Be careful! std::thread copies arguments by default. If you need to pass a reference (to modify a variable inside the thread), you must use std::ref().
void updateScore(int& score) {
score += 10;
}
int main() {
int currentScore = 0;
// std::thread t(updateScore, currentScore); // ERROR: Tries to copy, but function wants ref
std::thread t(updateScore, std::ref(currentScore)); // CORRECT: Wraps it safely
t.join();
// currentScore is now 10
}3. The Danger of Data Races
The Problem: Shared State Chaos 💥
Here is where multithreading stops being fun and starts being scary.
If two threads try to write to the same memory location (variable) at the same time, or one reads while another writes, you get a Data Race.
It is Undefined Behavior. Anything can happen. The value might be correct, it might be garbage, or the program might catch fire (metaphorically).
Why does this happen?
In C++, count++ looks like one operation. To the CPU, it is actually three:
- Load value from memory to register.
- Increment the register.
- Store register value back to memory.
If Thread A loads the value (say, 5), and before it saves 6, Thread B also loads the value (still 5), both will write 6. You lost an increment.
The Broken Counter Example
Try running this locally. You will almost never get 20,000.
#include <iostream>
#include <thread>
#include <vector>
int shared_counter = 0;
void increment() {
for (int i = 0; i < 10000; ++i) {
shared_counter++; // THE DANGER ZONE
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
// Expectation: 20000
// Reality: 14592? 19998? It changes every time.
std::cout << "Final Counter: " << shared_counter << std::endl;
return 0;
}4. Protecting Shared Data with Mutexes and Locks
The Solution: Mutual Exclusion (Mutex) 🔒
To fix the data race, we need to ensure that only one thread at a time can access the shared variable.
We use std::mutex (from <mutex>).
- Lock: "I am using this bathroom. Occupied."
- Unlock: "I am done. Free."
Concept: A mutex is like the key to the only bathroom in the coffee shop. If you have the key, no one else can enter. They have to wait outside (block) until you give back the key.
The Old Way (Manual Locking)
Not recommended for production, but good for understanding.
std::mutex mtx; // The door lock
void safe_increment() {
mtx.lock(); // Wait until lock is available, then take it
shared_counter++;
mtx.unlock(); // Release it. IMPORTANT!
}The Problem: If shared_counter++ throws an exception, or you hit a return statement before unlock(), the mutex remains locked forever. The program freezes (Deadlock).
The Industry Standard: RAII Locks (std::lock_guard) 🛡️
In C++, we hate remembering to close things manually. We use RAII (Resource Acquisition Is Initialization).
We wrap the mutex in a std::lock_guard.
- When
lock_guardis created, it callsmtx.lock(). - When
lock_guardgoes out of scope (function ends), it automatically callsmtx.unlock().
Even if the function crashes, the destructor runs and unlocks the mutex.
Final Correct Code
#include <iostream>
#include <thread>
#include <mutex> // Required for std::mutex
int shared_counter = 0;
std::mutex counter_mutex; // The guardian of the counter
void safe_increment() {
for (int i = 0; i < 10000; ++i) {
// Create a guard. This locks the mutex immediately.
// The scope (curly braces) dictates how long the lock is held.
std::lock_guard<std::mutex> lock(counter_mutex);
shared_counter++;
// lock_guard is destroyed here, automatically releasing the mutex.
}
}
int main() {
std::thread t1(safe_increment);
std::thread t2(safe_increment);
t1.join();
t2.join();
std::cout << "Final Counter: " << shared_counter << std::endl; // Always 20000
return 0;
}Summary Checklist ✅
- Include:
<thread>and<mutex>. - Lifecycle: Always
.join()your threads unless you have a very specific reason to.detach(). - Data: Identify shared data. If two threads write to it, you must protect it.
- Protection: Use
std::mutex. - Safety: Never manually lock/unlock. Use
std::lock_guardorstd::unique_lock.
📚 References & Extra Reading
Challenge
Task
You are given a C++ program that simulates 10 concurrent automated teller machines (ATMs) processing 1,000 deposits of $1 each into a single shared bank account. The current implementation suffers from a data race, causing the final balance to be incorrect and inconsistent.
Your task is to fix the program by implementing proper synchronization to ensure the final balance is always exactly $10,000.
Requirements
- Include the necessary header for mutual exclusion.
- Declare a global
std::mutexto protect the shared data. - Modify the
process_depositfunction to use astd::lock_guardto safely update theshared_account_balance. Do not use manuallock()andunlock()calls. - Do not modify the logic inside the
mainfunction.
Expected result
The corrected code should properly synchronize access to the shared_account_balance variable.
- The
<mutex>header must be included:#include <mutex>. - A global mutex instance must be declared:
std::mutex balance_mutex;. - The
process_depositfunction must be modified to usestd::lock_guard. The critical section where the balance is updated must be guarded, like this:
void process_deposit(double amount) {
for (int i = 0; i < 1000; ++i) {
std::lock_guard<std::mutex> lock(balance_mutex);
shared_account_balance += amount;
}
}Note: The for loop itself does not need to be inside the locked section, only the modification of the shared variable. However, for this specific problem structure, placing the lock guard inside the loop is the correct approach to ensure each increment is atomic.
The main function should remain unchanged. When executed, the corrected program will consistently output Final balance: 10000.