multithreading - ruby simple race condition question -
i came across example of race condition:
def inc(n) n + 1 end sum = 0 threads = (1..10).map thread.new 10_000.times sum = inc(sum) end end end threads.each(&:join) p sum
threads run in pararell , there's chance while 1 thread reads sum's value, 1 completes incrementing it, former finish own incrementing old value, , result sum won't change.
but wondering, why when replace line 'sum = inc(sum)' 'sum += 1', output appears correct.
why that?
is because overhead of calling method huge compared doing variable assignment , threads 'get out of sync' causing output incorrect?
i assume, straight sum += 1 still able observe race condition, if had been doing longer summing loop, etc.?
is because overhead of calling method huge compared doing variable assignment , threads 'get out of sync' causing output incorrect?
yes. verify it, increase counter , run several tests. increased 100_000.times
, here results:
$ seq 5 | xargs -l 1 ruby a.rb 100000 451167 472581 464413 442191 454204
well, doesn't seem nice, it?
so, yes, increment not atomic in ruby (and doubt there's lot of languages is). there helper classes implement such behavior; example, this one.
Comments
Post a Comment