2019-09-12 15:34:04 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class Thread
|
|
|
|
attr_accessor :origin
|
|
|
|
end
|
|
|
|
|
|
|
|
class ThreadDetective
|
|
|
|
def self.test_thread
|
|
|
|
Thread.new { sleep 1 }
|
|
|
|
end
|
2023-12-15 23:46:04 +08:00
|
|
|
|
2019-09-12 15:34:04 +08:00
|
|
|
def self.start(max_threads)
|
|
|
|
@thread ||= Thread.new { self.new.monitor(max_threads) }
|
|
|
|
|
|
|
|
@trace = TracePoint.new(:thread_begin) { |tp| Thread.current.origin = Thread.current.inspect }
|
|
|
|
@trace.enable
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.stop
|
|
|
|
@thread&.kill
|
|
|
|
@thread = nil
|
|
|
|
@trace&.disable
|
|
|
|
@trace.stop
|
|
|
|
end
|
|
|
|
|
|
|
|
def monitor(max_threads)
|
|
|
|
STDERR.puts "Monitoring threads in #{Process.pid}"
|
|
|
|
|
|
|
|
while true
|
|
|
|
threads = Thread.list
|
|
|
|
|
|
|
|
if threads.length > max_threads
|
|
|
|
str = +("-" * 60)
|
|
|
|
str << "#{threads.length} found in Process #{Process.pid}!\n"
|
|
|
|
|
|
|
|
threads.each do |thread|
|
|
|
|
str << "\n"
|
|
|
|
if thread.origin
|
|
|
|
str << thread.origin
|
|
|
|
else
|
|
|
|
str << thread.inspect
|
|
|
|
end
|
|
|
|
str << "\n"
|
|
|
|
end
|
|
|
|
str << ("-" * 60)
|
|
|
|
|
|
|
|
STDERR.puts str
|
|
|
|
end
|
|
|
|
sleep 1
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|