Class: NeocitiesRed::Services::Common::WorkerPool

Inherits:
Object
  • Object
show all
Defined in:
lib/neocities_red/services/common/worker_pool.rb

Overview

A simple thread pool for parallel task execution.

Processes a list of items concurrently using a fixed number of worker threads. Each item is passed to the block provided at construction time.

Examples:

pool = WorkerPool.new(5) { |item| puts item }
pool.process([1, 2, 3, 4, 5])

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(size) {|item| ... } ⇒ WorkerPool

Returns a new instance of WorkerPool.

Parameters:

  • size (Integer)

    number of concurrent worker threads

Yields:

  • (item)

    block to execute for each item

Yield Parameters:

  • item (Object)

    an item from the processing queue



22
23
24
25
# File 'lib/neocities_red/services/common/worker_pool.rb', line 22

def initialize(size, &block)
  @size = size
  @block = block
end

Instance Method Details

#process(items) ⇒ void

This method returns an undefined value.

Processes all items in the pool using worker threads.

Items are placed in a thread-safe queue and consumed by workers. The method blocks until all items have been processed.

Parameters:

  • items (Array<Object>)

    items to process



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/neocities_red/services/common/worker_pool.rb', line 34

def process(items)
  queue = Queue.new
  items.each { |item| queue << item }

  workers = Array.new(@size) do
    Thread.new do
      loop do
        item = queue.pop(true)
        @block.call(item)
      rescue ThreadError
        break
      end
    end
  end

  workers.each(&:join)
end