【问题标题】:Getting the current call stack from a different thread从不同的线程获取当前调用堆栈
【发布时间】:2014-10-13 19:52:39
【问题描述】:

在多线程情况下,是否有可能在某个线程t1 内从另一个线程t2t1 之外运行?如果有,怎么做?


回复 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 之间变化。

【问题讨论】:

  • t1.backtrace?
  • @Stefan 我不知道你是否按预期得到了我的问题,但如果我按照上面的代码尝试,我总是得到空数组,而我希望一些随机调用堆栈涉及一些来自abcd 方法调用。
  • 可能线程已经结束了,试试def d; sleep; end
  • @Stefan 是一样的。
  • 看来你得等一会儿(sleep 0.1)才能打电话给p t1.backtrace

标签: ruby multithreading callstack


【解决方案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

【讨论】:

    猜你喜欢
    • 2014-04-26
    • 1970-01-01
    • 2010-09-22
    • 2010-11-21
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 2017-11-27
    相关资源
    最近更新 更多