require 'thread' module Outlander class ThreadsPool def initialize(num_threads = 3) @num_threads = num_threads @queue = Queue.new end def enqueue(&task) @queue << task end def start raise "Could not start with empty queue" if @queue.empty? run_threads(@num_threads) sleep 1 until @queue.empty? && @queue.num_waiting == @num_threads end private def run_threads(num_threads = 1) 1.upto(num_threads) do Thread.new do while task = @queue.pop task.call end end end end end end