Last active
December 19, 2015 10:09
-
-
Save maxdeliso/5938181 to your computer and use it in GitHub Desktop.
asynchronous dispatcher in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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