我在 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/