How many thread?!

Hi list,

I’ve a question about threads counting… :slight_smile:


#!/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

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs