Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Thread#run and Thread#wakeup?

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 =)

like image 716
Saad Malik Avatar asked Oct 06 '12 20:10

Saad Malik


1 Answers

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
like image 194
Prakash Murthy Avatar answered Oct 15 '22 10:10

Prakash Murthy