Thread life cycle and its states in Ruby

RubyServer Side ProgrammingProgramming

In Ruby, we can create threads which have different states and a life cycle which denotes its time since it started till its ending. In this article, we will take a look at the life cycle of a thread in Ruby.

Thread Life Cycle in Ruby

The Thread life cycle is a brief summary of how the thread develops from the beginning to the end. With the help of Thread.new, Thread.fork, or Thread.start, a new thread can be created.

  • A new thread does not need to be started after creation. Whenever the CPU is available, it starts automatically.

  • A Thread object is returned by Thread.new. Threads can be queried and manipulated with several methods of the Thread class.

  • As soon as a thread reaches the block of code related to calling Thread.new, it stops.

  • By calling the value method of the Thread object, the last expression in the thread block is converted to the thread value, which is obtained by calling the last expression in the thread block.

  • A thread that runs completely will only receive a value from the value method. Otherwise, it will not receive a value.

  • In the event of an exception being raised, the thread is terminated. Only threads terminating with an exception will be affected by this condition, even if they are not main threads.

Thread States in Ruby

Ruby offers five thread states, each of which describe the thread's current status. To find out whether a thread is alive, use the alive? function and status methods.

The following table depicts the different Thread states in Ruby and their return values.

StatesReturn value
Runnablerun
SleepingSleep
Abortingaborting
Terminated normallyfalse
Terminated (Exception)nil

Let's explore a little more about these different states of a thread in Ruby.

  • Runnable − A thread that is running or waiting to take CPU resources if they become available.

  • Sleeping − An idle thread, one that is waiting for IO, or one that is currently stopped itself.

  • Aborting − A state in between. This refers to a thread that has been killed, but has not yet been terminated.

  • Terminated (Exception) − An exception containing thread, or another way of putting it, a thread that is terminated due to an exception occurring.

  • Terminated normally − When a thread finishes its work without containing an exception, or when it terminates normally.

Example

Now let's see a very basic example where we will create a new thread and then check its status. Consider the code shown below.

# status checking of a thread
cnt = 0

# new thread created
x = Thread.new {
   loop {
      cnt += 1
   }
}

# checking
puts x.alive?

# printing status
puts x.status

Output

true
run
raja
Updated on 25-Jan-2022 11:35:06

Advertisements