# How many thread?!

**URL:** <https://www.ruby-forum.com/t/how-many-thread/173014>\
**Category:** Ruby\
**Created:** [July 31, 2009, 10:34am UTC](https://www.ruby-forum.com/t/how-many-thread/173014 "2009-07-31T10:34:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![al\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f08c70/32.png) [@al\_S](https://www.ruby-forum.com/u/al_S)\
**Post date:** [July 31, 2009, 10:34am UTC](https://www.ruby-forum.com/t/how-many-thread/173014/1 "2009-07-31T10:34:27Z")

</div>

Hi list,

I’ve a question about threads counting… 🙂

* * *

#!/usr/bin/ruby

require ‘timeout’

timeout = 2  
server = %w(127.0.0.1 127.0.0.2 127.0.0.3 127.0.0.4)

def check (host,timeout)  
puts “checking… #{host}”  
timeout(timeout) do  
begin  
`/usr/bin/nslookup www.test.org #{host}`  
rescue Timeout::Error  
end  
end  
end

threads = []

server.each { |host|  
puts Thread.list.size  
threads \<\< Thread.new(host) { |host|  
check(host,timeout)  
}  
}

## threads.each {|th| th.join }

It will produces:

1  
checking… 127.0.0.1  
3  
checking… 127.0.0.2  
5  
checking… 127.0.0.3  
7  
checking… 127.0.0.4

7 threads for 4 requests?!

Without timeout:

1  
checking… 127.0.0.1  
2  
checking… 127.0.0.2  
3  
checking… 127.0.0.3  
4  
checking… 127.0.0.4

4 threads for 4 requests!

Why? Timeout produces a new threads?

Thank you,  
Al

---

<div class="post-metadata">

**Author:** ![al\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/f08c70/32.png) [@al\_S](https://www.ruby-forum.com/u/al_S)\
**Post date:** [July 31, 2009, 2:32pm UTC](https://www.ruby-forum.com/t/how-many-thread/173014/2 "2009-07-31T14:32:21Z")

</div>

Alfonso C. wrote:

> Why? Timeout produces a new threads?

Yes.

$ less /usr/lib/ruby/1.8/timeout.rb

…

def timeout(sec, exception=Error)  
return yield if sec == nil or sec.zero?  
raise ThreadError, “timeout within critical session” if  
Thread.critical  
begin  
x = Thread.current  
y = Thread.start {  
sleep sec  
x.raise exception, “execution expired” if x.alive?  
}  
yield sec  
# return true  
ensure  
y.kill if y and y.alive?  
end  
end

module\_function :timeout
