Difference between Thread#run and Thread#wakeup?

multithreading, ruby

Solution

The difference between `run` and `wakeup` in Ruby is exactly as described in the documentation, although the specifics of the MRI/YARV implementation are not mentioned. This makes sense, as there are other implementations of Ruby, like JRuby, that use "real" threads.

In Ruby, `wakeup` makes a thread schedulable, but it does not run the thread immediately. `run` also makes a thread schedulable, but it runs the thread immediately.

On MRI/YARV, it may initially appear that `wakeup` does nothing. This is because MRI/YARV has a GVL (Global VM Lock) that allows only one thread to run in the Ruby VM at a time and threads are not preempted in a traditional sense, but instead they run until they relinquish control (`Thread.pass`, `Kernel.sleep`, etc.), encounter an I/O wait or an interrupt flag is raised by the timer thread. In all cases, the thread scheduler resumes one of the other currently runnable threads. So, if you call `wakeup` and then either `Thread.pass` or cause an I/O wait (e.g. `gets`), you will see the other thread executing.

On MRI/YARV, `Thread.run` is essentially equivalent to `Thread.wakeup` + `Thread.pass` if there are only two threads. If there are more threads, `Thread.pass` may not necessarily start the woken-up thread, but rather the thread that the scheduler considers should run next. This is why the `run` method is necessary, as it both wakes up a thread and immediately runs it, without leaving it up to the scheduler. This is true for all implementations of Ruby, even those with "real" threads.

Problem

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

Original source