5.2.24 · HinglishC++ Programming

Concurrency — std - thread, std - mutex, std - lock_guard, std - unique_lock

1,673 words8 min readRead in English

5.2.24 · Coding › C++ Programming


Concurrency exist kyun karta hai?


Yeh chaar tools KIYA hain?


Inhe KAISE use karein — first principles se build karke

Step 1: Data race (bimari)

int counter = 0;
void add() { for (int i = 0; i < 100000; ++i) ++counter; }
 
int main() {
    std::thread t1(add), t2(add);
    t1.join(); t2.join();
    std::cout << counter; // NOT reliably 200000 — data race!
}

Yeh kyun toot ta hai: ++counter actually read → increment → write hai. Do threads in steps ko interleave karte hain, isliye increments lost ho jaate hain.

Step 2: Ilaaj — mutex se protect karo

int counter = 0;
std::mutex mtx;
void add() {
    for (int i = 0; i < 100000; ++i) {
        std::lock_guard<std::mutex> lk(mtx); // locks here
        ++counter;
    } // lk destroyed → unlock here, every iteration
}

Yeh kyun kaam karta hai: zyada se zyada ek thread guarded region ke andar hai; ++counter effectively atomic ban jaata hai. Result hamesha 200000 hota hai.

Figure — Concurrency — std - thread, std - mutex, std - lock_guard, std - unique_lock

Worked examples


Common mistakes


Flashcards

Data race kya hota hai?
Do threads ek hi memory location ko concurrently access karte hain, kam-se-kam ek likhta hai, aur koi synchronization nahi → undefined behavior.
Manual lock()/unlock() ki jagah lock_guard prefer kyun karein?
RAII guarantee karta hai ki unlock har scope exit par run hoga, exceptions aur early returns par bhi, deadlock prevent karta hai.
Agar ek joinable std::thread ko join/detach ke bina destroy kiya jaaye toh kya hoga?
std::terminate() call hoga, program abort ho jaayega.
lock_guard aur unique_lock mein antar?
lock_guard minimal hai: construction par lock, destruction par unlock, koi early control nahi. unique_lock flexible hai: defer/early unlock/relock, movable, condition variables ke saath kaam karta hai.
std::condition_variable ke saath unique_lock (na ki lock_guard) kyun pair karta hai?
cv.wait ko sote waqt unlock aur jagane par re-lock karna hota hai, jo sirf unique_lock allow karta hai.
Do mutexes ko deadlock ke risk ke bina kaise lock karein?
Dono ko std::defer_lock ke saath construct karo, phir std::lock(a, b) (ya C++17 mein std::scoped_lock(a,b)) se all-or-nothing acquire karo.
Kya std::thread copyable hai?
Nahi, yeh move-only hai; yeh ek unique OS thread resource own karta hai.
Hardware level par ++counter actually kya karta hai?
Counter read karo, increment karo, wapas write karo — teen steps jo threads ke beech interleave ho sakte hain.

Recall Feynman: 12-saal ke bache ko samjhao

Socho do bachche ek coloring book share kar rahe hain. Agar dono ek saath scribble karein, toh picture kharaab ho jaayegi — yahi data race hai. Toh ek rule banate hain: sirf ek crayon hai (mutex), aur coloring shuru karne se pehle use uthana padega aur baad mein wapas rakhna padega. lock_guard ek magic clip hai jo automatically crayon chhhod deta hai jis waqt tum chale jaate ho, taaki tum use kabhi accidentally hog na kar sako. unique_lock ek fancy clip hai jo tumhe crayon pehle bhi neeche rakhne deta hai agar tumhe break chahiye. Aur thread bas ek doosre bachche ko tumhare saath color karne ke liye invite karna hai — lekin table saaf karne se pehle tumhe kehna hoga "theek hai, ab tum done ho" (join), warna sab kuch gir jaayega.


Connections

  • RAII and resource management — lock_guard/unique_lock RAII ko locks par apply karte hain
  • std::atomic and lock-free programming — simple counters ke liye mutex ka alternative
  • std::condition_variableunique_lock chahiye
  • Deadlock and lock orderingstd::lock/scoped_lock kyun exist karte hain
  • std::async and std::future — raw std::thread ke comparison mein higher-level task launching
  • Undefined behavior in C++ — data races formally UB hain
  • Move semanticsstd::thread move-only kyun hai

Concept Map

enable

launches cooks

touch

unsynchronized causes

is

serializes access to

locks and unlocks

flexibly locks

uses

uses

prevents

works with

Multiple CPU cores

Concurrency

std thread

Shared memory access

Data race

Undefined behavior

std mutex

std lock_guard

std unique_lock

RAII scope exit unlock

Deadlock

condition_variable