cpp
#include <thread>
#include <mutex>
std::mutex mtx;
int counter = 0;
void increment(int n) {
for (int i = 0; i < n; ++i) {
std::lock_guard<std::mutex> lock(mtx); // RAII lock
++counter; // vùng critical section
} // lock tự mở khi ra scope
}
std::thread t1(increment, 1000);
std::thread t2(increment, 1000);
t1.join(); // chờ t1 hoàn thành
t2.join(); // chờ t2 hoàn thành
// counter == 2000 — thread-safeCác vấn đề cơ bản:
| Vấn đề | Mô tả | Giải pháp |
|---|---|---|
| Race condition | 2 thread cùng read-write shared data | mutex |
| Deadlock | 2 thread chờ nhau mãi | std::lock() + lock nhiều mutex cùng lúc |
| Thread leak | join()/detach() không được gọi | destructor của std::thread gọi terminate() |
std::lock_guard vs std::unique_lock: lock_guard đơn giản, không unlock sớm được; unique_lock linh hoạt hơn (có thể unlock(), dùng với condition variable).