Sha256: 6cdac91f3225d8e465eaaf2e0646d87ff886d1fbbf91b74d4d53228282d87a9b

Contents?: true

Size: 800 Bytes

Versions: 31

Compression:

Stored size: 800 Bytes

Contents

# frozen_string_literal: true

module ShopifyCLI
  class ThreadPool
    attr_reader :errors

    def initialize(pool_size: 10)
      @jobs = Queue.new
      @pool = Array.new(pool_size) { spawn_thread }
    end

    def schedule(job)
      @jobs << job
    end

    def shutdown
      @pool.size.times do
        schedule(-> { throw(:stop_thread) })
      end
      @pool.map(&:join)
    ensure
      @jobs.close
    end

    private

    def spawn_thread
      Thread.new do
        catch(:stop_thread) do
          loop { perform(@jobs.pop) }
        end
      end
    end

    def perform(job)
      job.call
      reschedule(job) if job.recurring?
    end

    def reschedule(job)
      wait(job.interval)
      schedule(job)
    end

    def wait(seconds)
      sleep(seconds)
    end
  end
end

Version data entries

31 entries across 31 versions & 1 rubygems

Version Path
shopify-cli-2.36.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.35.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.34.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.33.1 lib/shopify_cli/thread_pool.rb
shopify-cli-2.33.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.32.1 lib/shopify_cli/thread_pool.rb
shopify-cli-2.32.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.31.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.30.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.29.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.28.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.27.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.26.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.25.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.24.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.23.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.22.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.21.0 lib/shopify_cli/thread_pool.rb
shopify-cli-2.20.1 lib/shopify_cli/thread_pool.rb
shopify-cli-2.20.0 lib/shopify_cli/thread_pool.rb