Debian Codegraph @

core/lib/timelimitedqueue/timelimitedqueue.rb

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 =begin rdoc
3 コールバック機能付きキュー。コンストラクタに渡したブロックが、pushされた値の集合を引数に呼ばれる。
4 コールバックは、以下の条件の何れかを満たしたときに動く。
5 1. キューの個数が _max_ を超えたとき
6 2. キューに _expire_ 秒以上値の追加が無かったとき
7 =end
8
9 require 'thread'
10 require 'timeout'
11
12 class TimeLimitedQueue < Queue
13 extend Gem::Deprecate
14
15 TLQGroup = ThreadGroup.new
16 WaitingExpire = Class.new(Timeout::Error)
17
18 # 一度にキューを処理する上限を取得設定する
19 attr_accessor :max
20
21 # キューの待ち時間のリミットを取得設定する
22 attr_accessor :expire
23
24 # コールバックに渡すためのクラスを取得設定する。
25 # 通常Arrayだが、Setにすれば同じ値が同時に二つ入らない代わりに、高速に処理される。
26 # メソッド _push_ を実装しているクラスを指定する。
27 attr_accessor :storage_class
28 alias :strage_class :storage_class
29 deprecate :strage_class, "storage_class", 2019, 10
30 alias :strage_class= :storage_class=
31 deprecate :strage_class=, "storage_class=", 2019, 10
32
33 attr_reader :thread # :nodoc:
34
35 END{
36 TLQGroup.list.each{ |thread|
37 thread.kill if thread.alive?
38 thread[:queue].instance_eval{ callback } if thread[:queue] } }
39
40 def initialize(max=1024, expire=5, storage_class=Array, proc=nil, &block) # :yield: data
41 @thread = nil
42 @callback = proc || block
43 @max = max
44 @expire = expire
45 @storage_class = storage_class
46 @stock = @storage_class.new
47 super()
48 end
49
50 # 値 _value_ をキューに追加する。
51 def push(value)
52 result = super(value)
53 pushed_event
54 result end
55 undef_method(:enq, :<<)
56
57 private
58
59 # 待機中のスレッド内の処理
60 def waiting_proc
61 TLQGroup.add(Thread.current)
62 loop do
63 catch(:write) do
64 loop do
65 if @stock.size > max
66 throw :write
67 end
68 Timeout.timeout(expire, WaitingExpire){ @stock << pop }
69 rescue WaitingExpire
70 throw :write
71 end
72 end
73 callback if not @stock.empty?
74 break if empty?
75 end
76 end
77
78 def callback
79 # @stock.push(pop) while not empty?
80 stock = @stock.to_a
81 @callback.call(stock[0, max].freeze)
82 @stock = @storage_class.new(stock[max, stock.size] || []) end
83
84 # キューに値が追加された時のイベント
85 def pushed_event
86 if not(@thread and @thread.alive?)
87 @thread = Thread.new(&method(:waiting_proc))
88 TLQGroup.add(@thread)
89 @thread[:queue] = self
90 @thread.abort_on_exception = true
91 end end
92
93 end