这个简单的例子,我在JRuby上运行多线程,但它只有一个线程运行不能运行赛璐珞
require 'benchmark'
require 'celluloid/current'
TIMES = 10
def delay
sleep 1
# 40_000_000.times.each{|i| i*i}
end
p 'celluloid: true multithreading?'
class FileWorker
include Celluloid
def create_file(id)
delay
p "Done!"
File.open("out_#{id}.txt", 'w') {|f| f.write(Time.now) }
end
end
workers_pool = FileWorker.pool(size: 10)
TIMES.times do |i|
# workers_pool.async.create_file(i) # also not happens
future = Celluloid::Future.new { FileWorker.new.create_file(i) }
p future.value
end
所有创建的文件间隔1秒。
请帮助将赛璐珞变成多线程模式,其中所有文件都是同时创建的。
谢谢!
修复:
事实上,“期货”数组有助于!
futures = []
TIMES.times do |i|
futures << Celluloid::Future.new { FileWorker.new.create_file(i) }
end
futures.each {|f| p f.value }
感谢jrochkind!
在'create_file'的第一行中'delay'调用是怎么回事?我不确定'delay'方法是什么,我没有在Celluloid API中找到它。 – jrochkind
它的延迟功能,更正http://pastie.org/10447853 –