You're Always in a Thread
By default, your code is always running a thread. Even if you don’t create any new threads, there’s always at least one: the main thread.
You can use an irb
session to demonstrate this.
$ irb
> Thread.main
=> #<Thread:0x007fdc830677c0 run>
> Thread.current == Thread.main
=> true
The main thread is the original thread that’s created when you start a Ruby program. You can always create more threads, but you can’t change the reference to Thread.main
, it will always point to this original thread.
The main thread has one special property that’s different from other threads. When the main thread exits, all other threads are immediately terminated and the Ruby process exits. This is not true of any other thread besides the main thread.
thread = Thread.new do
# do the important work
end
# The main thread sleeps to prevent it from finishing execution.
# If it were allowed to run, it would simply exit, killing the other
# thread and preventing it from doing its important work.
sleep
The Thread.current
method always refers to the current thread. This may seem obvious, but you have to wrap your head around the fact that this one method will return a different Thread
object depending on which thread it’s called from.
This irb
session spawns a new thread, then compares Thread.current
with Thread.main
. Notice that in this case the two are no longer equal.
$ irb
> Thread.new { Thread.current == Thread.main }.value
=> false