ruby - Ruby Thread 的派生类?

标签 ruby multithreading

我在 C++ 世界生活了很多年,而我才刚刚开始使用 Ruby。我有一个类,我想做一个线程。在 Ruby 中,从 Thread 派生类是错误的吗?我看到的例子使用了下面的概念。

Thread.new { <some block> }

这样做会错吗?

class MyThread < Thread
  def initialize
  end

  def run
    <main loop>
  end

最佳答案

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

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

您可能想在您的领域中使用事件对象对某些概念进行建模。在那种情况下,标准 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 ...

关于ruby - Ruby Thread 的派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1053232/

相关文章:

ruby - Google Developer API key 和 YouTube API

c# - 使用 await 时 Monitor.Exit 上的 SynchronizationLockException

java - 如何加载数组中的图像以更快地显示android

ruby-on-rails - 在 Rails 应用程序的登录页面上显示提交编号

javascript - 从 JSON API 响应获取属性的唯一值计数

mysql - 获取分页查询中的结果总数

ruby-on-rails - fields_for、formtastic、ActiveMerchant 和验证错误

c++ - 从辅助线程启动可执行文件

java - 如何优雅地停止在Eclipse中运行的Java主程序

c# - 系统.线程.任务.并行