Robert Klemme
6/7/2007 8:33:00 PM
On 07.06.2007 22:03, Oliver Peng wrote:
> So when we call raise method, we are calling the MyThread instance's
> raise method and it stop running of MyThread instance. I tried to use
> Kernel.raise and Thread.current.raise. They all work fine and raise
> exception in main thread.
Basically whenever you invoke "raise" somewhere in code it's really
Kernel's raise which delegates to Thread.current.raise. As you see,
#raise is also an instance method of Thread so your situation was
special because your class inherited Thread. That's why the raise had a
slightly different effect, namely raising the exception in that thread
and not in the calling thread. Maybe this helps clarify:
irb(main):001:0> Thread.current.methods.grep /raise/
=> ["raise"]
irb(main):002:0> Thread.instance_methods.grep /raise/
=> ["raise"]
irb(main):003:0> method :raise
=> #<Method: Object(Kernel)#raise>
irb(main):004:0> Thread.current.method :raise
=> #<Method: Thread#raise>
It's often confusing when first confronted with multithreading in OO
languages like Ruby and Java: Thread's are instances (i.e. objects) like
all other objects but at the same time, there is a thread of execution
(i.e. stack, program counter etc.) associated with them. But this
relationship is not fixed: you can have Thread objects with no execution
thread associated. In Java this is between creation of a Thread
instance and invoking start() and after the thread terminated. In Ruby,
since threads are started immediately, it's only after a thread terminated.
Kind regards
robert