nat*_*han 8 ruby multithreading
我已经在C++世界生活多年了,我刚刚开始使用Ruby.我有一个班级,我想做一个线程.在Ruby中从Thread派生类是错误的吗?我看到的例子使用了以下概念.
Thread.new { <some block> }
Run Code Online (Sandbox Code Playgroud)
这样做会不对吗?
class MyThread < Thread
def initialize
end
def run
<main loop>
end
Run Code Online (Sandbox Code Playgroud)
Chr*_*ley 11
我认为这确实是关于域建模的问题.
如果你想扩展/增强线程的行为方式 - 例如添加调试或性能输出,那么你正在做的事情没有任何问题 - 但我认为这不是你想要的.
您可能希望使用活动对象在域中为某些概念建模.在这种情况下,标准的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 ...
Run Code Online (Sandbox Code Playgroud)
这很好,我见过人们之前就这么做过.以下是调用Thread.new时运行的Ruby邮件列表中的一些示例代码:
class MyThread < Thread
def initialize
super("purple monkey dishwasher") {|str| puts "She said, '#{str}.'"}
end
end
Run Code Online (Sandbox Code Playgroud)
如果您打算调用Thread.fork或Thread.start来运行您的线程,您应该从Ruby文档中了解这些方法:
"基本上与Thread :: new相同.但是,如果类是Thread子类,那么在该子类中调用start将不会调用子类的initialize方法."
我更喜欢这样封装:
class Threader
def initialize
@thread = Thread.new(&method(:thread))
end
private
def thread
# Do thready things...
end
end
Run Code Online (Sandbox Code Playgroud)
您也可以直接对Thread子类执行此操作:
class ThreadyThread < Thread
def initialize
super(&method(:thread))
end
private
def thread
# Do thready things...
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4012 次 |
| 最近记录: |