Ruby Thread的派生类?

前端之家收集整理的这篇文章主要介绍了Ruby Thread的派生类?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经在C世界生活多年了,我刚刚开始使用 Ruby.我有一个班级,我想做一个线程.在Ruby中从Thread派生类是错误的吗?我看到的例子使用了以下概念.
  1. Thread.new { <some block> }

这样做会有误吗?

  1. class MyThread < Thread
  2. def initialize
  3. end
  4.  
  5. def run
  6. <main loop>
  7. end

解决方法

我认为这确实是关于域建模的问题.

如果你想扩展/增强线程的行为方式,那么你正在做的事情没有任何问题 – 例如添加调试或性能输出,但我认为这不是你想要的.

您可能希望使用活动对象在域中为某些概念建模.在这种情况下,标准的Ruby方法更好,因为它允许您在不弯曲域模型的情况下实现此目的.

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

要使对象处于活动状态,请让它以某种方法捕获新创建的线程

  1. Class MyClass
  2.  
  3. ...
  4.  
  5.  
  6. def run
  7. while work_to_be_done do
  8. some_work
  9. end
  10. end
  11.  
  12. ...
  13.  
  14. end
  15.  
  16.  
  17. threads = []
  18.  
  19. # start creating active objects by creating an object and assigning
  20. # a thread to each
  21.  
  22. threads << Thread.new { MyClass.new.run }
  23.  
  24. threads << Thread.new { MyOtherClass.new.run }
  25.  
  26. ... do more stuff
  27.  
  28. # now we're done just wait for all objects to finish ....
  29.  
  30. threads.each { |t| t.join }
  31.  
  32.  
  33. # ok,everyone is done,see starships on fire off the shoulder of etc
  34. # time to die ...

猜你在找的Ruby相关文章