Hi,
I have a newbie question
If I run the following code outside a thread:
count=0
while count < 10000 do
puts โxโ
count +=1
end
I get 10000 โxโ.
But, if I run the same code inside a thread, I receive different number
of โxโ on each execution:
7932
4305
4431
What Iโm doing wrong?
I need to execute the same command inside a thread 10000 times!
Thank you.
Are you joinโing the thread? If not your main thread is likely to exit
before the counting thread has.
cat /tmp/test.rb
require โthreadโ
t = Thread.new {
count=0
while count < 10000 do
puts โxโ
count +=1
end
}
t.join
ruby /tmp/test.rb |wc -l
10000
ruby /tmp/test.rb |wc -l
10000
ruby /tmp/test.rb |wc -l
10000
Sam
Hi,
That was the problem! I have to reread the threat chapter of the ruby
book
Thank you.
Sam D. wrote in post #1013619:
Are you joinโing the thread? If not your main thread is likely to exit
before the counting thread has.
cat /tmp/test.rb
require โthreadโ
t = Thread.new {
count=0
while count < 10000 do
puts โxโ
count +=1
end
}
t.join
ruby /tmp/test.rb |wc -l
10000
ruby /tmp/test.rb |wc -l
10000
ruby /tmp/test.rb |wc -l
10000
Sam
No worries. You are on the doorstep of an exciting and endlessly
frustrating world. Have fun =]
Sam
Miguel Angel Nieto wrote in post #1013621:
That was the problem! I have to reread the threat chapter of the ruby
book
You can also use Thread#value which does an implicit join like this:
irb(main):003:0> t = Thread.new do
irb(main):004:1* count = 0
irb(main):005:1> while count < 1000
irb(main):006:2> count += 1
irb(main):007:2> end
irb(main):008:1> count
irb(main):009:1> end; t.value
=> 1000
Kind regards
robert