Threads & Mutex in C++

From the C++ cheat sheet · Concurrency · verified Jul 2026

Threads & Mutex

Running work in parallel safely.

cpp
// Quick Reference
#include <thread>
#include <mutex>
std::thread t([]{ work(); });
t.join();
std::mutex m;
std::lock_guard<std::mutex> lock(m);
💡 Every std::thread must be joined or detached before it is destroyed, or the program aborts.
⚡ std::jthread (C++20) auto-joins on destruction - prefer it over raw std::thread.
📌 Guard shared data with std::lock_guard/scoped_lock - RAII unlocks even on exceptions.
🟢 Unsynchronized access to shared mutable data from multiple threads is a data race (UB).
threadsmutex

More C++ tasks

Back to the full C++ cheat sheet