Reputation: 168189
Given a thread (that is not dead):
t = Thread.new{sleep}
is it possible to add some code, given as a proc for example, and run that within t
?
Upvotes: 2
Views: 137
Reputation: 6041
Perhaps by using a thread variable and waiting until it's defined:
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
Which will output:
Next round..
Next round..
Next round..
Next round..
Next round..
Next round..
hello there!
But if you're asking if you can break the Thread.new {sleep} from sleeping and inserting something else for it to run, I don't know, maybe by using 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
Upvotes: 6