Lesson 5 of 7
std::thread Basics - Concurrency Introduction
`std::thread` (C++11) represents a thread of execution. Creating a thread is simple; safely **sharing data** between threads is hard. The critical concept: **data races** (two threads accessing the same data with at least one write, without synchronisation) are **undefined behaviour** in C++. `std::mutex` + `std::lock_guard` provide mutual exclusion. `std::atomic<T>` provides lock-free access to simple types. This section gives you the foundation - full concurrency is a deep topic deserving its own study.
std::thread, std::mutex, std::lock_guard & std::atomic
#define _POSIX_C_SOURCE 200809L
#include <iostream>
#include <thread>
#include <mutex>
#include <atomic>
#include <vector>
#include <string>
// ── Thread creation - pass function + arguments ───────────────
void worker(int id, int iterations) {
for (int i = 0; i < iterations; ++i) {
// do work
}
std::cout << "Worker " << id << " done
";
}
// ── Shared data without protection - DATA RACE (BAD) ─────────
// int counter = 0;
// void increment_unsafe() { counter++; } // NOT atomic! UB on concurrent access
// ── Mutex protection ──────────────────────────────────────────
std::mutex g_mutex;
int g_counter = 0;
void increment_safe() {
std::lock_guard<std::mutex> lock(g_mutex); // RAII lock
++g_counter;
// lock released automatically on scope exit
}
// ── std::atomic - lock-free for simple types ─────────────────
std::atomic<int> g_atomic_counter{0};
void increment_atomic() {
++g_atomic_counter; // atomic: no mutex needed for simple increment
// std::atomic guarantees sequential consistency for ++ by default
}
// ── Thread with lambda and captured by ref ────────────────────
void launch_threads_demo() {
std::vector<std::thread> threads;
// Spawn 4 threads
for (int i = 0; i < 4; ++i) {
threads.emplace_back(worker, i, 100); // pass args directly
}
// MUST join or detach every thread before destruction
for (auto& t : threads) {
t.join(); // wait for completion
}
}
void mutex_demo() {
std::vector<std::thread> threads;
g_counter = 0;
g_atomic_counter = 0;
for (int i = 0; i < 4; ++i) {
threads.emplace_back([](){
for (int j = 0; j < 1000; ++j) {
increment_safe();
increment_atomic();
}
});
}
for (auto& t : threads) t.join();
std::cout << "mutex counter: " << g_counter << "
"; // 4000
std::cout << "atomic counter: " << g_atomic_counter << "
"; // 4000
}
// ── Thread safety key concepts ────────────────────────────────
// - Data race = two threads, same memory, at least one write, no sync → UB
// - std::mutex: mutual exclusion - only one thread at a time
// - std::lock_guard: RAII mutex - never forget to unlock
// - std::unique_lock: more flexible than lock_guard (try_lock, defer)
// - std::atomic<T>: lock-free atomic operations for simple types
// - std::condition_variable: thread signalling (producer/consumer)
//
// For production C++: study memory ordering, happens-before,
// std::promise/future, std::async, coroutines (C++20)
int main() {
std::cout << "--- thread launch ---
";
launch_threads_demo();
std::cout << "
--- mutex + atomic ---
";
mutex_demo();
// Hardware concurrency hint
std::cout << "hardware_concurrency: "
<< std::thread::hardware_concurrency() << "
";
return 0;
}
// Compile: g++ -std=c++17 -Wall -O2 -pthread thread_demo.cppCommon Mistakes
- Forgetting to `join()` or `detach()` - if a thread object is destroyed while the thread is still running, `std::terminate()` is called. Always join or detach every thread before the `std::thread` object goes out of scope.
- Sharing data without synchronisation - `counter++` on a non-atomic `int` from two threads is a data race and undefined behaviour. The compiled code for `++counter` is typically 3 instructions (load, add, store) - another thread can interleave between them. Use `std::atomic<int>` or `std::mutex`.
- Using `std::cout` without a mutex in a multi-threaded program - `std::cout` is thread-safe in the sense that individual characters won't be corrupted, but output from different threads can interleave in the same line. Use a mutex around each complete output sequence for clean output.
Tip
Tip
Practice stdthread Basics Concurrency Introduction in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Multithreaded execution, mutex locks, condition variables, and futures
Practice Task
Note
Practice Task - (1) Write a working example of stdthread Basics Concurrency Introduction from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with stdthread Basics Concurrency Introduction is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- `std::thread` (C++11) represents a thread of execution.
- Forgetting to `join()` or `detach()` - if a thread object is destroyed while the thread is still running, `std::terminate()` is called. Always join or detach every thread before the `std::thread` object goes out of scope.
- Sharing data without synchronisation - `counter++` on a non-atomic `int` from two threads is a data race and undefined behaviour. The compiled code for `++counter` is typically 3 instructions (load, add, store) - another thread can interleave between them. Use `std::atomic<int>` or `std::mutex`.
- Using `std::cout` without a mutex in a multi-threaded program - `std::cout` is thread-safe in the sense that individual characters won't be corrupted, but output from different threads can interleave in the same line. Use a mutex around each complete output sequence for clean output.
Finished this lesson?