Skip to content

Instantly share code, notes, and snippets.

@Malet
Created October 13, 2015 09:16
Show Gist options
  • Save Malet/dbbc5090ce6f9b57abc8 to your computer and use it in GitHub Desktop.
Save Malet/dbbc5090ce6f9b57abc8 to your computer and use it in GitHub Desktop.
ThreadPool
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
@Malet
Copy link
Author

Malet commented Oct 13, 2016

2.1.1 :044 > ThreadPool.new(input_array: %w(hello world), callback: ->(item) { item * 2 }, threads: 10).run
 => ["hellohello", "worldworld"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment