Class: PMap::ThreadPool

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

Instance Method Summary collapse

Constructor Details

#initialize(max) ⇒ ThreadPool

Public: Initializes a new thread pool

max - the maximum number of threads to spawn

Raises:

  • (ArgumentError)


21
22
23
24
25
26
27
28
# File 'lib/pmap/thread_pool.rb', line 21

def initialize(max)
  raise ArgumentError, "max must be at least one." unless
    max.respond_to?(:>=) && max >= 1

  @max = max
  @jobs = Queue.new
  @workers = []
end

Instance Method Details

#schedule(*args, &job) ⇒ Object

Public: Schedules a new job to run in a thread

*args - any arguments that will be passed to the block &job - the block that will be executed on the thread



35
36
37
38
# File 'lib/pmap/thread_pool.rb', line 35

def schedule(*args, &job)
  @jobs << [job, args]
  spawn_worker if @workers.size < @max
end

#shutdownObject

Public: Shuts down the thread pool and waits for any running threads to

complete


43
44
45
46
47
48
# File 'lib/pmap/thread_pool.rb', line 43

def shutdown
  @workers.size.times do
    @jobs << :stop_working
  end
  @workers.each(&:join)
end