how many thread?!

A

Alfonso Caponi

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
 
B

Brian Candler

Alfonso said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,019
Latest member
RoxannaSta

Latest Threads

Top