Created
October 13, 2015 09:16
-
-
Save Malet/dbbc5090ce6f9b57abc8 to your computer and use it in GitHub Desktop.
ThreadPool
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
class ThreadPool | |
def initialize(input_array:, callback:, threads: 128) | |
@callback, @input_array, @threads = callback, input_array, threads | |
end | |
def run | |
results = [] | |
input_queue, results_queue = Queue.new, Queue.new | |
@input_array.each{ |item| input_queue << item } | |
workers = (1..@threads).map do | |
Thread.new do | |
begin | |
while item = input_queue.pop(true) | |
results_queue << @callback.call(item) | |
end | |
rescue ThreadError | |
end | |
end | |
end | |
# Move data into a regular array | |
workers.map(&:join) | |
results_queue.length.times{ results << results_queue.pop } | |
results | |
end | |
end |
Author
Malet
commented
Oct 13, 2016
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment