⚡C++AdvancedLesson 45 of 50CamboFreelanceJune 19, 2026
C++ Multithreading
Introduction to C++ multithreading: std::thread, mutex, lock_guard, async, and future. Write safe concurrent programs.
Advanced12 min readLesson 45 of 50
std::thread (C++11)
C++11 introduced native threading via <thread>. Compile with -std=c++11 -pthread.
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void task(int id) {
cout << "Thread " << id << " starting\n";
this_thread::sleep_for(chrono::milliseconds(100 * id));
cout << "Thread " << id << " done\n";
}
int main() {
thread t1(task, 1);
thread t2(task, 2);
thread t3(task, 3);
t1.join(); // wait for t1 to finish
t2.join();
t3.join();
cout << "All threads completed." << endl;
return 0;
}
Mutex — Preventing Race Conditions
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;
int counter = 0;
void increment(int n) {
for (int i = 0; i < n; i++) {
lock_guard<mutex> lock(mtx); // auto-unlocks when out of scope
counter++;
}
}
int main() {
thread t1(increment, 10000);
thread t2(increment, 10000);
t1.join(); t2.join();
cout << "Counter: " << counter << endl; // 20000 (thread-safe)
return 0;
}
std::async and std::future
#include <future>
auto result = async(launch::async, []() {
// heavy computation
int sum = 0;
for (int i = 1; i <= 1000000; i++) sum += i;
return sum;
});
cout << "Result: " << result.get() << endl; // blocks until done
Warning: Always join() or detach() threads before they go out of scope. Destroying a joinable thread calls std::terminate().
Exercise
Create two threads: one prints even numbers 0–10, the other prints odd numbers 1–9. Use a mutex to prevent interleaved output.
Show Solution
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex print_mtx;
void printEvens() {
for (int i = 0; i <= 10; i += 2) {
lock_guard<mutex> lock(print_mtx);
cout << "Even: " << i << endl;
}
}
void printOdds() {
for (int i = 1; i <= 9; i += 2) {
lock_guard<mutex> lock(print_mtx);
cout << "Odd: " << i << endl;
}
}
int main() {
thread t1(printEvens), t2(printOdds);
t1.join(); t2.join();
return 0;
}
Quiz
What is a race condition?
A) A thread running too fast
B> Multiple threads accessing shared data without synchronization, causing unpredictable results
C) Thread deadlock
D> Thread starvation
Answer
B) A race condition occurs when multiple threads access/modify shared data concurrently without proper synchronization.
Summary
std::thread creates concurrent threads; join() waits for them.
Use mutex with lock_guard to prevent race conditions.
std::async runs tasks asynchronously and returns a future.