从不同的线程获取当前调用堆栈

时间:2014-08-20 12:41:41

标签: ruby multithreading callstack

在多线程情况下,是否可以在t1之外的另一个线程t2内的某个线程t1内获取调用堆栈?如果是这样,怎么样?

<小时/>

对Stefan的回应:

我试过了:

def a; b end
def b; c end
def c; d end
def d; sleep(1) end
t1 = Thread.new do
  100.times{a}
end
p t1.backtrace

但它总是返回一个空数组[]

<小时/>

编辑:

根据Stefan的建议,以下参数适用于我的电脑:

def a; b end
def b; c end
def c; d end
def d; end
t1 = Thread.new do
  1000.times{a}
end
sleep(0.0001)
p t1.backtrace

它返回一个随机调用堆栈,其中最顶层的方法在ad之间变化。

1 个答案:

答案 0 :(得分:1)

您可以调用Thread#backtrace,但显然线程需要一些时间才能启动:

def baz
  loop until @baz
end

def bar
  baz
  loop until @bar
end

def foo
  bar
  loop until @foo
end

t1 = Thread.new { foo }

sleep 0.1                # wait for the thread
p t1.backtrace

@baz = true; sleep 0.1   # exit 3rd method
p t1.backtrace

@bar = true; sleep 0.1   # exit 2nd method
p t1.backtrace

@foo = true; sleep 0.1   # exit 1st method
p t1.backtrace

输出:

["thread.rb:2:in `baz'", "thread.rb:6:in `bar'", "thread.rb:11:in `foo'", "thread.rb:15:in `block in <main>'"]
["thread.rb:7:in `bar'", "thread.rb:11:in `foo'", "thread.rb:15:in `block in <main>'"]
["thread.rb:12:in `foo'", "thread.rb:15:in `block in <main>'"]
nil