我正在编写一个可以ping我的ip范围的脚本.这是我到目前为止所拥有的:
lines = `ipconfig`.split("\n")
thr = []
ip_line = lines.detect { |l| l=~/Ip Address/i }
matcher = /\d+\.\d+\.\d+\.\d+/.match(ip_line)
if matcher.length > 0
address = matcher[0]
address.sub!(/\.\d+$/,"")
(1 .. 254).each do |i|
xaddr = address + "." + i.to_s
puts "pinging #{xaddr}"
thr << Thread.new {
`ping #{xaddr}`
}
end
thr.each do |t|
t.join
output = t.value
puts output
end
end
Run Code Online (Sandbox Code Playgroud)
问题是,这执行得非常慢.就像应用程序没有线程.这是为什么?我注意到如果我将Thread子类化,整个事情运行得更快,更快.怎么了?Thread不是直接用的吗?