Debian Codegraph @

core/serialthread.rb

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 require_relative 'utils'
4
5 require 'delayer'
6 require 'delayer/deferred'
7 require 'set'
8 require 'thread'
9 require 'timeout'
10
11 # 渡されたブロックを順番に実行するクラス
12 class SerialThreadGroup
13 QueueExpire = Class.new(Timeout::Error)
14
15 # ブロックを同時に処理する個数。最大でこの数だけThreadが作られる
16 attr_accessor :max_threads
17
18 @@force_exit = false
19
20 def initialize(max_threads: 1, deferred: nil)
21 @lock = Monitor.new
22 @queue = Queue.new
23 @max_threads = max_threads
24 @deferred_class = deferred
25 @thread_pool = Set.new
26 end
27
28 # 実行するブロックを新しく登録する
29 # ==== Args
30 # [proc] 実行するブロック
31 def push(proc=nil, &block)
32 proc ||= block
33 promise = @deferred_class && @deferred_class.new(true)
34 return promise if @@force_exit
35 @lock.synchronize{
36 @queue.push(proc: proc, promise: promise)
37 new_thread if 0 == @queue.num_waiting and @thread_pool.size < max_threads }
38 promise
39 end
40 alias new push
41
42 # 処理中なら真
43 def busy?
44 @thread_pool.any?{ |t| :run == t.status.to_sym } end
45
46 # 全てのserial threadの実行をキャンセルする。終了時の処理用
47 def self.force_exit!
48 notice "all Serial Thread Group jobs canceled."
49 @@force_exit = true end
50
51 private
52
53 # Threadが必要なら一つ立ち上げる。
54 # これ以上Threadが必要ない場合はtrueを返す。
55 def flush
56 return true if @@force_exit
57 @lock.synchronize{
58 @thread_pool.delete_if{ |t| not t.alive? }
59 if @thread_pool.size > max_threads
60 return true
61 elsif 0 == @queue.num_waiting and @thread_pool.size < max_threads
62 new_thread end }
63 false end
64
65 def new_thread
66 return if @@force_exit
67 @thread_pool << Thread.new do
68 while node = Timeout.timeout(1, QueueExpire){ @queue.pop }
69 break if @@force_exit
70 result = node[:proc].call
71 node[:promise].call(result) if node[:promise]
72 break if flush
73 debugging_wait
74 Thread.pass
75 end
76 rescue QueueExpire, ThreadError
77 rescue Object => e
78 if node[:promise]
79 node[:promise].fail(e)
80 else
81 error e
82 abort
83 end
84 ensure
85 @lock.synchronize do
86 @thread_pool.delete(Thread.current)
87 end
88 end
89 end
90
91 end
92
93 # SerialThreadGroup のインスタンス。
94 # 同時実行数は1固定
95 SerialThread = SerialThreadGroup.new