From: Robert Klemme Date: 2010-11-17T17:57:06+09:00 Subject: Re: Thread problem On Wed, Nov 17, 2010 at 9:16 AM, Justin Collins wrote: > On 11/16/2010 11:50 PM, Jaeyong Lee wrote: >> >> 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. >> >> > > http://en.wikipedia.org/wiki/Race_condition#Computing > > You are updating a shared variable "simultaneously" in separate threads, > which is a very bad idea. 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: threads = [] 1.upto(1000) { |external| threads << Thread.new(external) { |local| sleep(rand(0.01)) local } } sum = 0 threads.each() { |thread| sum += thread.value()} puts sum Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/