Multithreading in C++
Multithreading is the ability of a program to execute multiple parts of code (called threads) simultaneously. It improves performance by making better use of CPU cores, allowing tasks to run in parallel.
What is a Thread?
A thread is the smallest unit of execution within a process.
When a C++ program runs, the operating system creates a main thread that starts executing the main() function.
Other threads can be created by the program to perform different tasks at the same time.
- Each thread runs independently but shares the same memory space with other threads in the same process.
- Because they share memory, threads can communicate easily but must avoid overwriting each other's data.
What is Multithreading?
Multithreading means running two or more threads concurrently within the same program. For example:
- One thread handles user input
- Another thread processes data
- Another thread updates the screen
Multithreading vs. Multiprocessing
- Multithreading: Multiple threads share the same memory space inside a single process.
- Multiprocessing: Multiple processes run separately, each with its own memory space.
How C++ Implements Multithreading
C++11 introduced the <thread> library, which provides built-in support for creating and managing threads in a platform-independent way.
Before C++11, multithreading depended on operating system APIs like:
- Windows:
CreateThread()API - POSIX systems (Linux/Unix):
pthreadlibrary
std::thread.
// Example: Creating two threads in C++
#include <iostream>
#include <thread>
void task1() {
std::cout << "Task 1 is running\n";
}
void task2() {
std::cout << "Task 2 is running\n";
}
int main() {
std::thread t1(task1);
std::thread t2(task2);
t1.join(); // Wait for thread 1 to finish
t2.join(); // Wait for thread 2 to finish
return 0;
}
Thread Management
- join() — Makes the main thread wait for a thread to finish before continuing.
- detach() — Allows a thread to run independently (in the background) without blocking the main thread.
Synchronization
Since threads share memory, conflicts can occur if two threads try to read/write the same variable at the same time. To avoid this, C++ provides:
- mutex — Locks a resource so only one thread can access it at a time.
- lock_guard — Simplifies mutex usage by automatically locking/unlocking.
- condition_variable — Allows threads to wait and notify each other.
// Example: Using mutex for thread safety
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void safe_print(const std::string &msg) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << msg << std::endl;
}
int main() {
std::thread t1(safe_print, "Hello from Thread 1");
std::thread t2(safe_print, "Hello from Thread 2");
t1.join();
t2.join();
}
Advantages of Multithreading
- Better CPU utilization
- Faster execution for parallel tasks
- Improved program responsiveness
Disadvantages and Risks
- Complex code — harder to debug
- Risk of race conditions and deadlocks
- Requires careful synchronization
Use Cases
- Web servers handling multiple requests
- Real-time gaming and simulation
- Parallel data processing
- Multimedia applications (video/audio processing)