Long loops inside threads

Hi,

I have a newbie question :slight_smile:

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! :slight_smile:

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 :wink:

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 :wink:

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