#
# Author:: Ranjib Dey (<ranjib@pagerduty.com>)
# Copyright:: Copyright (c) 2014 PagerDuty, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'thread'
require 'blender/log'

module Blender
  module Utils
    class ThreadPool
      def initialize(size)
        @size = size
        @queue = Queue.new
      end

      def add_job(&blk)
        @queue << blk
      end

      def run_till_done
        num = @size > @queue.size ? @queue.size : @size
        threads = Array.new(num) do
          Thread.new do
            Thread.current.abort_on_exception = true
            @queue.pop.call while true
          end
        end
        until @queue.empty?
          sleep 0.2
        end
        until @queue.num_waiting == num
          sleep 0.2
        end
        threads.each do |thread|
          thread.join(0.02)
        end
        threads.map(&:kill)
      end
    end
  end
end
