我正在编写一个脚本来 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
问题是,这执行得非常慢。就像应用程序没有线程一样。这是为什么?我注意到,如果我将 Thread 子类化,整个事情的运行速度会快得多。怎么了?Thread 不是用于直接使用吗?