2009-06-27 53 views
8

我住在C++的世界里,和我刚开始使用Ruby。我有一门课我想做一个线程。在Ruby中,从Thread中派生类是错误的?我看到的例子使用了下面的概念。派生类的Ruby线程?

Thread.new { <some block> } 

这样做是错误的吗?

class MyThread < Thread 
    def initialize 
    end 

    def run 
    <main loop> 
    end 

回答

9

我认为这确实是一个关于域名的建模问题。

会有什么不妥,如果你想扩展/增强,一个线程的行为方式,你在做什么 - 比如添加调试或性能输出,但我不认为这是你想要的。

你可能要建模与活动对象域的一些概念。在这种情况下,标准Ruby方法更好,因为它可以让您在不弯曲域模型的情况下实现这一点。

继承真的应该只用于IS_A关系建模。这个标准的ruby代码整洁地包装了解决方案。

为了让你的对象主动,有它捕捉到新创建的线程在一些方法

Class MyClass 

... 


    def run 
     while work_to_be_done do 
     some_work 
     end 
    end 

... 

end 


threads = [] 

# start creating active objects by creating an object and assigning 
# a thread to each 

threads << Thread.new { MyClass.new.run } 

threads << Thread.new { MyOtherClass.new.run } 

... do more stuff 

# now we're done just wait for all objects to finish .... 

threads.each { |t| t.join } 


# ok, everyone is done, see starships on fire off the shoulder of etc 
# time to die ... 
6

这非常好,我以前见过这样的人。下面是从运行Ruby的邮件列表,一些示例代码时Thread.new叫做:

class MyThread < Thread 
    def initialize 
    super("purple monkey dishwasher") {|str| puts "She said, '#{str}.'"} 
    end 
end 

如果你打算叫Thread.fork或Thread.start运行你的线程,你应该意识到这一点从Ruby documentation those methods

“基本上和Thread :: new一样。但是,如果Thread类是子类,那么调用该子类中的start将不会调用子类的initialize方法。

+0

我猜C++程序员在我身上。是否确定在Ruby中运行的线程出来的构造?通常情况下,这将永远不会在C++中完成的。 – nathan 2009-06-28 00:34:27

+0

我同意这有点奇怪,但它突出了Ruby给你的灵活性。这是一个好主意吗?这有点奇怪,但它肯定是被班级和语言所允许的,并且非常可读。其他人指出,这不是标准的事情,但我不认为这是有史以来最糟糕的事情,可能有一个应用程序,这是完美的。 – 2009-06-28 06:11:40

+0

+1对于你回答詹姆斯。你回答了所问的问题。克里斯实际上让我意识到我有一个域问题。因此,获奖的答案就交给他了。 – nathan 2009-06-28 12:32:35

0

它不是一个真正的红宝石的方式,但它取决于你试图与线程完成的任务。

首先,红宝石1.8并没有真正有真正的线程,所以他们才真正有用的IO绑定的东西。

一般在红宝石你想要的东西在一个线程中执行的操作,而不是代表一个线程,所以它更容易定义,创建内部线程来处理线程方面的普通类。

继承是一个IS_A关系

1

线程Ruby文档中提到“如果线程子类”,所以它看起来像它应该罚款。确保如果你的覆盖初始化,你叫超强!

5

我更喜欢这样做封装:

class Threader 
    def initialize 
    @thread = Thread.new(&method(:thread)) 
    end 

private 

    def thread 
    # Do thready things... 
    end 
end 

你也可以这样做直接的Thread子类:

class ThreadyThread < Thread 
    def initialize 
    super(&method(:thread)) 
    end 

private 

    def thread 
    # Do thready things... 
    end 
end