如何获取另一个线程的调用堆栈?

How do I get a call stack of another thread?

是否可以从一个线程获得另一个线程的 Kernel#caller 输出?或者更好的是来自后台主线程的堆栈,这对我来说可以作为一种分析器。

有 Thread#backtrace 方法可以获取某个线程的函数回溯:

https://ruby-doc.org/core-2.4.1/Thread.html#method-i-backtrace

backtrace → array click to toggle source

Returns the current backtrace of the target thread.

使用示例检查此项目:https://github.com/frsyuki/sigdump(它将显示 ruby 和 jruby 的回溯和一些内存使用信息)

sigdump - In short: SIGQUIT of Java VM for Ruby (Use signal to show stacktrace of a Ruby process without restarting it).

... Just sending SIGCONT signal will dump backtrace and memory profile to /tmp/sigdump-.log file.

sigdump dumps following information (see also Sample output):

Backtrace of all threads

https://github.com/frsyuki/sigdump/blob/master/lib/sigdump.rb

    dump_all_thread_backtrace(io)
...
    Thread.list.each do |thread|
      dump_backtrace(thread, io)
...
  def self.dump_backtrace(thread, io)
    status = thread.status
    if status == nil
      status = "finished"
    elsif status == false
      status = "error"
    end

    io.write "  Thread #{thread} status=#{status} priority=#{thread.priority}\n"
    if thread.backtrace
      thread.backtrace.each {|bt|
        io.write "      #{bt}\n"
      }
    end

    io.flush
    nil
  end