Sha256: 492fa40d3f6c6948ed8790f8eaa8e80ddcc0f4d7139601f19c9e9f17ab3089b0

Contents?: true

Size: 847 Bytes

Versions: 3

Compression:

Stored size: 847 Bytes

Contents

# frozen_string_literal: true

module Spandx
  module Core
    class ThreadPool
      def initialize(size: Etc.nprocessors)
        @size = size
        @queue = Queue.new
        @pool = size.times.map { start_worker_thread }
      end

      def schedule(*args, &block)
        @queue.enq([block, args])
      end

      def done?
        @queue.empty?
      end

      def shutdown
        @size.times do
          schedule { throw :exit }
        end

        @pool.map(&:join)
      end

      def self.open
        pool = new
        yield pool
      ensure
        pool.shutdown
      end

      private

      def start_worker_thread
        Thread.new do
          catch(:exit) do
            loop do
              job, args = @queue.deq
              job.call(*args)
            end
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
spandx-0.13.2 lib/spandx/core/thread_pool.rb
spandx-0.13.1 lib/spandx/core/thread_pool.rb
spandx-0.13.0 lib/spandx/core/thread_pool.rb