Concept | Header | Summary |
Threads | <thread> | Standard, low-level, type-safe; |
Futures | <future> | Via async function, hides threading; |
Locks | <mutex> | Standard, low-level locking primitives |
Condition Vars | <condition_variable> | Low-level synchronization primitives |
Atomics | <atomic> | Predictable, concurrent access without data race |
- How to avoid data races
- redesign to eliminate sharing data
- use thread-safe entities(e.g. parallel collections)
- use synchronization(e.g. lock atom...)
- Using RAII( Resource Acquisition Is Initialization ) to avoid data races
old style
#include <mutex> #include <thread> std::mutex m; int sum = 0; std::thread t1( [&] () { int r = func(); m.lock(); sum += r; m.unlock(); });
using RAII
std::mutex m; int sum = 0; std::thread t1( [&] () { int r = func(); { lock_guard<mutex> locker(m); sum += r; } });