Reputation: 2111
I am trying the following code from a threading example in Ruby:
count = 0
arr = []
10.times do |i|
arr[i] = Thread.new {
sleep(count*10)
Thread.current["mycount"] = count
count += 1
}
end
arr.each {|t| t.join; print t["mycount"], ", " }
puts "count = #{count}"
Because I increase the sleep on each thread, I expect the output to be in order from 1-10, However in almost all runs, the order is random. Why ?
Upvotes: 0
Views: 1900
Reputation: 1522
The order is random because the access of the object count
is not synchronized amongst threads.
You are encountering what is called a Race Condition
A race condition occurs when two or more threads can access shared data and they try to change it at the same time.
You can stop this through using mutex, condition variables and queue objects within ruby.
EDIT: Also, see Jeremy's answer
Upvotes: 0
Reputation: 16355
You are only updating count
after the thread finishes sleeping, so all of the threads read the initial value of count
, which is 0, when they go to sleep.
It's also worth noting that accessing count
in this way is not threadsafe.
Upvotes: 1