Class: Tobox::ThreadedPool

Inherits:
Pool
  • Object
show all
Defined in:
lib/tobox/pool/threaded_pool.rb

Instance Method Summary collapse

Methods inherited from Pool

#do_work

Constructor Details

#initialize(_configuration) ⇒ ThreadedPool

Returns a new instance of ThreadedPool.



7
8
9
10
11
12
# File 'lib/tobox/pool/threaded_pool.rb', line 7

def initialize(_configuration)
  @parent_thread = Thread.main
  @threads = []
  @threads.extend(MonitorMixin)
  super
end

Instance Method Details

#startObject



14
15
16
17
18
19
20
21
# File 'lib/tobox/pool/threaded_pool.rb', line 14

def start
  @workers.each do |wk|
    th = start_thread_worker(wk)
    @threads.synchronize do
      @threads << th
    end
  end
end

#stopObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/tobox/pool/threaded_pool.rb', line 23

def stop
  shutdown_timeout = @configuration[:shutdown_timeout]
  grace_shutdown_timeout = @configuration[:grace_shutdown_timeout]

  super
  Thread.pass # let workers finish

  # soft exit
  join = lambda do |timeout|
    start = Process.clock_gettime(::Process::CLOCK_MONOTONIC)

    loop do
      terminating_th = @threads.synchronize { @threads.first }

      return unless terminating_th

      elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start

      break if elapsed > timeout

      terminating_th.join(timeout - elapsed)
    end
  end

  join.call(shutdown_timeout)

  # hard exit
  @threads.synchronize { @threads.each { |th| th.raise(KillError) } }
  join.call(grace_shutdown_timeout)
  @threads.synchronize { @threads.each(&:kill) }
  join.call(1)
end