-->

Difference between Thread#run and Thread#wakeup?

2020-08-26 10:56发布

问题:

In Ruby, what is the difference between Thread#run and Thread#wakup?

The RDoc specifies that scheduler is not invoked with Thread#wakeup, but what does that mean? An example of when to use wakeup vs run? Thanks.

EDIT:
I see that Thread#wakup causes the thread to become runnable, but what use is it if the it's not going to execute until Thread#run is executed (which wakes up the thread anyway)?

Could someone please provide an example where wakeup does something meaningful? For curiosity's sake =)

回答1:

Here is an example to illustrate what it means (Code example from here):

Thread.wakeup

thread = Thread.new do 
  Thread.stop
  puts "Inside the thread block"
end

$ thread
=> #<Thread:0x100394008 sleep> 

The above output indicates that the newly created thread is asleep because of the stop command.

$ thread.wakeup
=> #<Thread:0x100394008 run>

This output indicates that the thread is not sleeping any more, and can run.

$ thread.run
Inside the thread block
=> #<Thread:0x1005d9930 sleep>   

Now the thread continues the execution and prints out the string.

$ thread.run
ThreadError: killed thread

Thread.run

thread = Thread.new do 
  Thread.stop
  puts "Inside the thread block"
end

$ thread
=> #<Thread:0x100394008 sleep> 

$ thread.run
Inside the thread block
=> #<Thread:0x1005d9930 sleep>   

The thread not only wakes up but also continues the execution and prints out the string.

$ thread.run
ThreadError: killed thread