From: Robert Klemme Date: 2008-10-06T23:39:26+09:00 Subject: Re: Concurent (using threads) slower than sequential -doubt 2008/10/6 Carlos Ortega : > Thank all of you (Matz, Charles and Robert) > > Just one more doubt..... > > Since the threads I created really resides as an array that holds > threads object I tried to access each one by using [ ] notation: > > for t in m_threads > print t[:INDEX], "\n" > end > > The interpreter does not throw any error, but results always indicate: > nil > nil > nil > > I tried to verify if they are still running: > > Thread.list.each{|t| p t} > > Results were: > # > # > # > # > > So indeed they are running... the doubt is...why I can't access the > content of the array? > In fact in the statement > m_threads.each{ |t| t.join; result = t[:INDEX] + result; } > > I just can compute result variable only after executing t.join..... if > I take out the t.join statement the interpreter throws an error: > > PbaThreads.rb:10 : undefined method `+' for nil:NilClass (NoMethodError) > > Could you clarify this, please. Well, this is obvious: you cannot access the result before it's there. Since you are setting this as the last statement in the thread you need to wait (i.e. join) until the thread finishes. Btw, you can use Thread#value for this. Here's a variant: require 'benchmark' files = (1..3).map {|i| "C:\\numbers#{i}.txt"} Benchmark.bmbm 10 do |b| b.report "threaded" do threads = files.map do |file| Thread.new file do |f| File.open f do |io| io.inject(0) {|sum, l| sum + l.to_i} end end end puts threads.inject(0) {|sum, th| sum + th.value} end b.report "sequential" do puts files.inject(0) {|s, f| File.open f do |io| io.inject(s) {|sum, l| sum + l.to_i} end } end end Kind regards robert -- remember.guy do |as, often| as.you_can - without end