为什么这样运行就像没有线程? [英] Why is this running like it isn't threaded?

查看:57
本文介绍了为什么这样运行就像没有线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个可ping通IP地址范围的脚本.这是我到目前为止的内容:

I'm writing a script that will ping my ip range. Here's what I have so far:

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子类化,则整个过程将运行得非常快得多.怎么了?线程不打算直接使用吗?

The thing is, this executes extremely slow. Like the app isn't threaded. Why is that? I noticed that if I subclass Thread, the whole thing runs much, much faster. What's wrong? Isn't Thread intended for direct usage?

推荐答案

Ruby线程由Ruby Interpreter控制.对于操作系统,Ruby Interpreter仍然只是一个进程(就像其他任何进程一样). Ruby Interpreter将该进程分为多个红宝石线程.

Ruby threads are controlled by Ruby Interpreter. to operating system, Ruby Interpreter is still just one process(just like any other processes). Ruby Interpreter split that one process into multiple ruby threads.

`ping #{xaddr}`  

此行强制Ruby Interpreter暂时放弃其控制,因为您要让操作系统执行另一个进程.直到"ping"完成后,红宝石解释器才会重新获得控制.这可能就是为什么代码很慢的原因.

this line forces the Ruby Interpreter to temporarily give up its control, since you are asking the operating system to execute another process. The ruby interpreter will not regain its control until after the 'ping' finishes. That's probably why the code is slow.

这篇关于为什么这样运行就像没有线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆