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
counter?synchronize method to safely run code blocks.mutex.synchronize { ... } is the correct syntax to lock and unlock automatically.require 'thread'
mutex = Mutex.new
counter = 0
threads = 5.times.map do
Thread.new do
10.times do
mutex.synchronize { counter += 1 }
end
end
end
threads.each(&:join)
puts countercounter = 0
threads = 3.times.map do
Thread.new do
100.times { counter += 1 }
end
end
threads.each(&:join)
puts counterresults from multiple threads in Ruby. Which approach correctly ensures thread safety?mutex.synchronize ensures only one thread writes at a time.Pass the test and this pattern moves unknown