Skip to content

Commit 42bba1a

Browse files
authored
Merge pull request #6 from jjb/spool-down-threads-when-exiting
Spool down threads when exiting
2 parents a1d26e5 + 82e57c8 commit 42bba1a

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

lib/stathat.rb

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ class Reporter
7575

7676
def initialize
7777
@que = Queue.new
78-
@runlock = Mutex.new
7978
run_pool
8079
end
8180

@@ -111,12 +110,10 @@ def ez_post_count(stat_name, ezkey, count, timestamp, cb)
111110
private
112111

113112
def run_pool
114-
@runlock.synchronize { @running = true }
115113
@pool = []
116114
5.times do |i|
117115
@pool[i] = Thread.new do
118-
while true do
119-
point = @que.pop
116+
while point = @que.pop do
120117
# XXX check for error?
121118
begin
122119
resp = Common::send_to_stathat(point[:url], point[:args])
@@ -126,23 +123,21 @@ def run_pool
126123
rescue
127124
pp $!
128125
end
129-
@runlock.synchronize do
130-
break unless @running
131-
end
132126
end
133127
end
134128
end
135129
end
136130

137131
def stop_pool
138-
@runlock.synchronize { @running = false }
132+
@que.close
133+
139134
@pool.each do |th|
140-
th.join if th && th.alive?
135+
th.join(5)
141136
end
142137
end
143138

144139
def enqueue(url, args, cb=nil)
145-
return false unless @running
140+
return false if @que.closed?
146141
point = { url: url, args: args, cb: cb }
147142
@que << point
148143
true
@@ -182,3 +177,11 @@ def parse
182177
end
183178
end
184179
end
180+
181+
%w[INT TERM].each do |signal|
182+
old_handler = trap(signal) do
183+
puts "StatHat::Reporter.instance.finish in response to #{signal}"; STDOUT.flush
184+
StatHat::Reporter.instance.finish
185+
old_handler.call if old_handler.respond_to?(:call)
186+
end
187+
end

0 commit comments

Comments
 (0)