Вы можете использовать очередь заданий, например, resque
. Придумали несколько быстрых примеров для чистого ruby
, разветвив дочерний процесс
rd, wr = IO.pipe
p1 = fork do
rd.close
# sleep is for demonstration purpose only
sleep 10
# the forked child process also has a copy of the open file
# handles, so we close the handles in both the parent and child
# process
wr.write "1"
wr.close
end
wr.close
puts "Process detaching | #{Time.now}"
Process.detach(p1)
puts "Woot! did not block | #{Time.now}"
1.upto(10) do
begin
result = rd.read_nonblock(1)
rescue EOFError
break
rescue Exception
# noop
end
puts "result: #{result.inspect}"
system("ps -ho pid,state -p #{p1}")
sleep 2
end
rd.close
__END__
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.6.0]
Process detaching | 2012-02-28 17:05:49 +0530
Woot! did not block | 2012-02-28 17:05:49 +0530
result: nil
PID STAT
5231 S+
result: nil
PID STAT
5231 S+
result: nil
PID STAT
5231 S+
result: nil
PID STAT
5231 S+
result: nil
PID STAT
5231 S+
result: "1"
PID STAT
при наличии обратного вызова в потоке
require 'thread'
Thread.abort_on_exception = true
module Deferrable
def defer(&block)
# returns a thread
Thread.new do
# sleep is for demonstration purpose only
sleep 10
val = block.call
# this is one way to do it. but it pollutes the thread local hash
# and you will have to poll the thread local value
# can get this value by asking the thread instance
Thread.current[:human_year] = val
# notice that the block itself updates its state after completion
end
end
end
class Dog
include Deferrable
attr_accessor :age, :human_age
attr_accessor :runner
def initialize(age=nil)
@age = age
end
def calculate_human_age_as_deferred!
self.runner = defer do
# can do stuff with the values here
human_age = dog_age_to_human_age
# and finally publish the final value
after_defer { self.human_age = human_age }
# return value of the block. used in setting the thread local
human_age
end
end
protected
def dog_age_to_human_age
(self.age / 7.0).round(2)
end
def after_defer(&block)
block.call
end
end
dog = Dog.new(8)
dog.calculate_human_age_as_deferred!
1.upto(10) do
sleep 2
puts "status: #{dog.runner.status} | human_age: #{dog.human_age.inspect}"
break unless dog.runner.status
end
puts "== using thread local"
dog = Dog.new(8)
dog.calculate_human_age_as_deferred!
1.upto(10) do
sleep 2
puts "status: #{dog.runner.status} | human_age: #{dog.runner[:human_year].inspect}"
break unless dog.runner.status
end
__END__
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.6.0]
status: sleep | human_age: nil
status: sleep | human_age: nil
status: sleep | human_age: nil
status: sleep | human_age: nil
status: false | human_age: 1.14
== using thread local
status: sleep | human_age: nil
status: sleep | human_age: nil
status: sleep | human_age: nil
status: sleep | human_age: nil
status: false | human_age: 1.14
потребляет меньше памяти, чем разветвление дочернего процесса, но разветвление надежно.Необработанная ошибка в потоке может разрушить всю систему.в то время как необработанная ошибка в дочернем процессе приведет к останову только дочернего процесса
Другие люди указали на наличие волокон и событийную машину (используя EM :: Deferrable и EM.defer) - еще один вариант
Волокна и нити нуждаются в тщательном кодировании.тонкий код может быть неправильным.
Кроме того, волокна используют упреждающую многозадачность, поэтому кодовая база должна хорошо себя вести.
Eventmachine быстр, но это эксклюзивный мир (например, витой в python).Он имеет свой отдельный стек ввода-вывода, поэтому все библиотеки должны быть написаны для поддержки Eventmachine.Сказав это, я не думаю, что поддержка библиотеки является проблемой для eventmachine