Class: Puma::ThreadPool

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

Overview

A simple thread pool management object.

Defined Under Namespace

Classes: AutoTrim

Constant Summary collapse

Stop =
Object.new
Trim =
Object.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(min, max, &blk) ⇒ ThreadPool

Maintain a minimum of min and maximum of max threads in the pool.

The block passed is the work that will be performed in each thread.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/puma/thread_pool.rb', line 14

def initialize(min, max, &blk)
  @todo = Queue.new
  @mutex = Mutex.new

  @spawned = 0
  @min = min
  @max = max
  @block = blk

  @trim_requested = 0

  @workers = []

  @auto_trim = nil

  min.times { spawn_thread }
end

Instance Attribute Details

#spawnedObject (readonly)

Returns the value of attribute spawned.



32
33
34
# File 'lib/puma/thread_pool.rb', line 32

def spawned
  @spawned
end

Instance Method Details

#<<(work) ⇒ Object

Add work to the todo list for a Thread to pickup and process.



82
83
84
85
86
87
88
# File 'lib/puma/thread_pool.rb', line 82

def <<(work)
  if @todo.num_waiting == 0 and @spawned < @max
    spawn_thread
  end

  @todo << work
end

#auto_trim!(timeout = 5) ⇒ Object



126
127
128
129
# File 'lib/puma/thread_pool.rb', line 126

def auto_trim!(timeout=5)
  @auto_trim = AutoTrim.new(self, timeout)
  @auto_trim.start!
end

#backlogObject

How many objects have yet to be processed by the pool?



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

def backlog
  @todo.size
end

#shutdownObject

Tell all threads in the pool to exit and wait for them to finish.



133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/puma/thread_pool.rb', line 133

def shutdown
  @auto_trim.stop if @auto_trim

  @spawned.times do
    @todo << Stop
  end

  @workers.each { |w| w.join }

  @spawned = 0
  @workers = []
end

#spawn_threadObject

:nodoc:



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/puma/thread_pool.rb', line 44

def spawn_thread
  @mutex.synchronize do
    @spawned += 1
  end

  th = Thread.new do
    todo = @todo
    block = @block

    while true
      work = todo.pop

      case work
      when Stop
        break
      when Trim
        @mutex.synchronize do
          @trim_requested -= 1
        end

        break
      else
        block.call work
      end
    end

    @mutex.synchronize do
      @spawned -= 1
      @workers.delete th
    end
  end

  @mutex.synchronize { @workers << th }

  th
end

#trimObject

If too many threads are in the pool, tell one to finish go ahead and exit.



93
94
95
96
97
98
99
100
# File 'lib/puma/thread_pool.rb', line 93

def trim
  @mutex.synchronize do
    if @spawned - @trim_requested > @min
      @trim_requested += 1
      @todo << Trim
    end
  end
end