I think that the reason of this problem is the simultaneous use of a
common resource. In your example, the common resource is the variable
*sum*. You need to use a Mutex object to avoid the simultaneous use of
that variable.
cf. Mutex class: http://ruby-doc.org/core/classes/Mutex.html
···
---
require 'thread'
threads =
sum = 0
mutex = Mutex.new
1.upto(1000) { |external|
threads << Thread.new(external) { |local|
sleep(rand(0.01))
mutex.synchronize {
sum = sum + local
}
}
}
threads.each() { |thread| thread.join() }
puts sum
---
2010/11/17 Jaeyong Lee <crizin@gmail.com>:
Hi all,
I learning ruby thread and faced to thread problem.
Here's my test code that sum 1 to 1000.
--
threads =
sum = 0
1.upto(1000) { |external|
threads << Thread.new(external) { |local|
sleep(rand(0.01))
sum = sum + local
}
}
threads.each() { |thread| thread.join() }
puts sum
--
I expected '500500' but output is smaller than. (ex: 499864)
Please let me know what problem is.
Absolutely correct. In this particular case using a shared resource
is not necessary since the state of that shared resource is only
accessed when all threads have terminated. One could do this as well: