C++ Multithreading Basics — Complete Beginner Guide
Learning Objectives
- Launch and join worker threads
- Identify shared state race conditions
- Protect critical sections with mutex
- Know when atomic variables are enough
Why Threads Exist
Threads let one process perform overlapping work. One thread can wait on user input while another computes or downloads. On multi core machines, independent tasks can progress at the same time. The power comes with responsibility: shared memory needs synchronization.
Creating Threads
The thread type starts a concurrent path of execution.
#include <iostream>
#include <thread>
void worker() {
std::cout << "working in a thread" << std::endl;
}
int main() {
std::thread t(worker);
t.join();
return 0;
}
| Call | Meaning |
|---|---|
| thread constructor | Start running the target |
| join | Wait until that thread finishes |
| detach | Let it run independently |
| joinable | Whether a wait is still possible |
Always join or otherwise resolve joinable threads before destruction. Destroying a joinable thread typically calls terminate.
Passing Data to Threads
You can pass values or references. Reference passing requires that the data outlive the thread's need for it.
#include <thread>
#include <iostream>
void show(int value) {
std::cout << value << std::endl;
}
int main() {
std::thread t(show, 42);
t.join();
return 0;
}
Lambdas work well when several captures define the task.
int limit = 3;
std::thread t([limit]() {
for (int i = 0; i < limit; i++) {
// process step
}
});
t.join();
The Race Condition Problem
When two threads write the same memory without coordination, the result depends on timing. That is a data race. Lost updates are a classic symptom.
// unsafe pattern without locks
counter = counter + 1; // read, modify, write can interleave
Interleaved read modify write sequences can drop increments. Bugs appear only on some runs, which makes testing harder.
mutex for Mutual Exclusion
A mutex is a lock. Only one thread holds it at a time, creating a critical section.
#include <mutex>
#include <thread>
#include <iostream>
std::mutex m;
int counter = 0;
void add() {
for (int i = 0; i < 1000; i++) {
std::lock_guard<std::mutex> lock(m);
counter += 1;
}
}
int main() {
std::thread a(add);
std::thread b(add);
a.join();
b.join();
std::cout << counter << std::endl;
return 0;
}
lock_guard locks on construction and unlocks on destruction, even if an exception interrupts the block. That is RAII for locks.
| Lock Style | Notes |
|---|---|
| lock_guard | Simple scoped lock |
| unique_lock | Flexible lock and unlock control |
| lock multiple | Coordinate several mutexes carefully |
atomic for Simple Flags and Counters
Atomic types guarantee indivisible operations for their supported widths. They shine for flags, counters, and simple counters without complex invariants.
#include <atomic>
#include <thread>
std::atomic<int> hits{0};
void bump() {
hits.fetch_add(1);
}
| Tool | Good For |
|---|---|
| mutex | Multiple variables or longer critical work |
| atomic | Single small values and flags |
| condvar later | Waiting for state changes |
Atomics are not a universal replacement for locks when your invariant spans several fields.
Avoiding Deadlocks
Deadlock happens when threads wait on each other forever. Prevent it by locking in a consistent global order, keeping critical sections short, and avoiding calls that may lock again while already holding a lock.
// safer habit: one order for every code path
std::lock_guard<std::mutex> lock(m);
// minimal work only
Thread Lifecycle Rules
- Start with a clear target function or lambda
- Join before scope end unless you intentionally detach
- Do not touch joined threads as if running
- Share data only with protection or true immutability
A Slightly Larger Example
#include <atomic>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
int main() {
std::mutex m;
std::atomic<int> atomicHits{0};
int guardedHits = 0;
auto work = [&]() {
for (int i = 0; i < 1000; i++) {
atomicHits.fetch_add(1);
std::lock_guard<std::mutex> lock(m);
guardedHits += 1;
}
};
std::vector<std::thread> pool;
for (int i = 0; i < 4; i++) {
pool.emplace_back(work);
}
for (auto& t : pool) {
t.join();
}
std::cout << "atomic: " << atomicHits << std::endl;
std::cout << "guarded: " << guardedHits << std::endl;
return 0;
}
Both totals should match the expected count when synchronization is correct.
Common Mistakes
| Mistake | Result |
|---|---|
| Forgetting join | Premature terminate risk |
| Unsynchronized shared writes | Data race and wrong totals |
| Locking too long | Poor performance or priority issues |
| Using atomic for complex state | Still need careful ordering |
| Destroying thread while running joinable | Terminate behavior |
Key Takeaways
💡
- std::thread starts work; join waits for completion
- Shared mutable state needs mutex or suitable atomic protection
- lock_guard provides RAII locking that unlocks on scope exit
- Data races cause timing dependent bugs that tests often miss
- Keep critical sections small and lock order consistent
Practice Questions
- What does join do and why must it usually run before scope end?
- Describe a simple data race using a shared counter.
- When is atomic preferable to a mutex?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions