Module: CMDx::Executors::Thread Private

Extended by:
Thread
Included in:
Thread
Defined in:
lib/cmdx/executors/thread.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Default executor. Uses a fixed-size ‘Thread` pool drained via a `Queue`; sentinel `nil`s terminate workers. Workers inherit the parent’s chain via fiber-local storage. Exceptions raised inside ‘on_job` are captured per worker and re-raised on the main thread once every worker has joined, so callers see failures instead of silently dropped jobs.

Instance Method Summary collapse

Instance Method Details

#call(jobs:, concurrency:, on_job:) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Parameters:

  • jobs (Array)

    opaque job objects forwarded to ‘on_job`

  • concurrency (Integer)

    worker count (must be >= 1)

  • on_job (#call)

    unary callable invoked per job

Raises:

  • (ArgumentError)

    when ‘concurrency` is not a positive Integer

  • (StandardError)

    re-raises the first exception captured from any worker



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/cmdx/executors/thread.rb', line 22

def call(jobs:, concurrency:, on_job:)
  raise ArgumentError, "executor concurrency must be a positive Integer (got #{concurrency.inspect})" unless concurrency.is_a?(Integer) && concurrency.positive?

  queue  = Queue.new
  errors = Queue.new

  jobs.each { |job| queue << job }
  concurrency.times { queue << nil }

  workers = Array.new(concurrency) do
    ::Thread.new do
      while (job = queue.pop)
        begin
          on_job.call(job)
        rescue StandardError => e
          errors << e
        end
      end
    end
  end

  workers.each(&:join)

  raise errors.pop unless errors.empty?
end