Skip to content

Instantly share code, notes, and snippets.

@maxdeliso
Last active December 19, 2015 10:09
Show Gist options
  • Save maxdeliso/5938181 to your computer and use it in GitHub Desktop.
Save maxdeliso/5938181 to your computer and use it in GitHub Desktop.
asynchronous dispatcher in ruby
# http://stackoverflow.com/questions/17499021/io-bound-threads-in-ruby
require 'thread'
class PoisonPill; end
def asyncDispatcher(numWorkers, stateArray, &processor)
q = Queue.new
threads = []
(1..numWorkers).each do
threads << Thread.new(processor) do |processor|
while true
next_state = q.shift # blocks if q is empty, which is the case initially
break if next_state.is_a? PoisonPill # causes all workers to stop
processor.call(next_state)
end
end
end
stateArray.each {|state| q.push state} # load the queue with initial states
stateArray.each {q.push PoisonPill.new} # add the poison pill.
threads.each(&:join) # wait for remaining workers
return # avoid returning useless thread refs
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment