将代码添加到现有线程

时间:2013-11-17 17:18:16

标签: ruby multithreading

给定一个帖子(没有死):

t = Thread.new{sleep}

是否可以添加一些代码,例如作为proc给出,并在t内运行?

1 个答案:

答案 0 :(得分:6)

也许通过使用线程变量并等待它被定义:

a = Thread.new do
  while Thread.current["proc"].nil?
    sleep 0.5
    puts "Next round.."
  end
  Thread.current["proc"].call
end

sleep 3

a["proc"] = Proc.new { puts "hello there!" }

a.join

将输出:

Next round..
Next round..
Next round..
Next round..
Next round..
Next round..
hello there!

但是如果你问你是否可以将Thread.new {sleep}从睡眠状态中分解出来并插入其他东西来运行它,我不知道,也许是通过使用thread.raise:

class ExceptionWithProc < StandardError
  attr_accessor :proc
end

a = Thread.new {sleep rescue $!.proc.call}

exception = ExceptionWithProc.new
exception.proc = Proc.new { puts "hello there!" }

sleep 3

a.raise(exception)
a.join
相关问题