Multithreading

CSC-264 · Semester IV · Operating Systems

Thread Lifecycle & Race Conditions

Drive threads through New → Runnable → Running → Blocked → Terminated.

Thread-0 (counter++)

thread 0

New

Thread-1 (counter++)

thread 1

New

Thread-2 (I/O wait)

thread 2

New

Shared counter

0

Why races happen

1. Thread-A: LOAD counter → sees 7

2. Thread-B: LOAD counter → sees 7

3. Thread-A: ADD 1 → 8

4. Thread-B: ADD 1 → 8

5. Thread-A: STORE 8

6. Thread-B: STORE 8 — one increment lost!

The fix: mutex / atomic increment

Wrap the read–modify–write in a mutex lock, or use an atomic fetch_add, so only one thread touches the counter at a time. On your machine this is what pthread mutexes and Java's synchronized provide.