Class: Fontisan::Utils::ThreadPool

Inherits:
Object
  • Object
show all
Defined in:
lib/fontisan/utils/thread_pool.rb

Overview

Simple thread pool implementation

Manages a fixed number of worker threads for parallel job execution. Jobs are queued and processed by available workers.

Examples:

Basic usage

pool = ThreadPool.new(4)
future = pool.schedule { expensive_computation }
result = future.value
pool.shutdown

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ ThreadPool

Initialize thread pool

Parameters:

  • size (Integer)

    Number of worker threads



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/fontisan/utils/thread_pool.rb', line 19

def initialize(size)
  @size = size
  @queue = Queue.new
  @threads = []
  @shutdown = false

  # Start worker threads
  @size.times do
    @threads << Thread.new { worker_loop }
  end
end

Instance Method Details

#schedule { ... } ⇒ Future

Schedule a job for execution

Yields:

  • Job to execute

Returns:

  • (Future)

    Future object to retrieve result



35
36
37
38
39
# File 'lib/fontisan/utils/thread_pool.rb', line 35

def schedule(&block)
  future = Future.new
  @queue << { block: block, future: future }
  future
end

#shutdownObject

Shutdown thread pool

Waits for all queued jobs to complete and stops workers.



44
45
46
47
48
49
50
51
52
# File 'lib/fontisan/utils/thread_pool.rb', line 44

def shutdown
  @shutdown = true

  # Signal all threads to stop
  @size.times { @queue << :stop }

  # Wait for all threads to finish
  @threads.each(&:join)
end