Class: ThreadPool

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

Defined Under Namespace

Classes: Job

Instance Method Summary collapse

Constructor Details

#initialize(min, max = nil) ⇒ ThreadPool

Returns a new instance of ThreadPool.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/filbunke/thread_pool.rb', line 8

def initialize(min, max = nil)
  
  trap("INT") { shutdown }

  @min = min
  @max = max || min

  @cv = ConditionVariable.new
  @mutex = Mutex.new

  @queue = []
  @workers = []

  @spawned = 0
  @waiting = 0
  @shutdown = false
  @queue_locked = false

  @mutex.synchronize do
    min.times { spawn_thread }
  end
end

Instance Method Details

#execute(*args, &block) ⇒ Object Also known as: <<



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/filbunke/thread_pool.rb', line 31

def execute(*args, &block)
  @mutex.synchronize do
    raise "Thread pool is about to shutdown" if @shutdown || @queue_locked

    @queue << Job.new(args, block)

    spawn_thread if @waiting == 0 && @spawned < @max

    @cv.signal
  end
end

#joinObject



53
54
55
56
57
58
59
60
# File 'lib/filbunke/thread_pool.rb', line 53

def join
  @mutex.synchronize do
    @queue_locked = true
    @cv.broadcast
    sleep 0.01 until @queue.empty?
  end
  shutdown
end

#shutdownObject



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

def shutdown
  @mutex.synchronize do
    @shutdown = true
    @cv.broadcast
  end

  @workers.first.join until @workers.empty?
end