Concept Flow - Thread safety concepts
Start Thread 1
Access shared data
Modify shared data
Race condition?
Data corrupted
End
Two threads try to access and modify shared data at the same time, which can cause conflicts unless controlled.
counter = 0 threads = [] 5.times do threads << Thread.new do 1000.times { counter += 1 } end end threads.each(&:join) puts counter
| Step | Thread | Action | counter before | counter after | Note |
|---|---|---|---|---|---|
| 1 | T1 | Read counter | 0 | 0 | Reads current counter value 0 |
| 2 | T1 | Add 1 | 0 | 1 | Adds 1 to local value |
| 3 | T2 | Read counter | 0 | 0 | Reads counter before T1 writes |
| 4 | T1 | Write counter | 0 | 1 | Writes updated counter 1 |
| 5 | T2 | Add 1 | 0 | 1 | Adds 1 to local value |
| 6 | T2 | Write counter | 0 | 1 | Overwrites counter with 1, lost increment |
| ... | ... | ... | ... | ... | ... |
| Final | All | After all increments | ? | less than 5000 | Counter less than expected due to race conditions |
| Variable | Start | After T1 step 2 | After T2 step 6 | Final |
|---|---|---|---|---|
| counter | 0 | 1 | 1 | <5000 (less than expected) |
Thread safety means controlling access to shared data Without control, threads can overwrite each other (race condition) Use Mutex or locks to allow one thread at a time This prevents lost updates and data corruption Always protect shared variables in multithreaded code