Ruby

Ruby Create a New Thread

A thread is a single unit of execution in a program. An ordinary program is single-threaded, where the instructions in the program execute successively until termination.

On the other hand, multi-threading allows the program to create multiple threads where instructions in a program can execute concurrently. It offers excellent utilization of system resources such as CPU and memory.

In Ruby, we use threads with the help of the Threads class. Threads in Ruby are not resource-heavy, making them efficient for employing concurrency in your programs.

Threads are implemented within the Ruby interpreter for Ruby version 1.9 and below. As of version 1.9 and above, threading is implemented on the Operating system.

Using this guide, you will learn how to implement threads in Ruby programming.

POINT OF NOTE: Matz’s Interpreter (MRI) has a Global Interpreter Lock that stops multiple threads from running simultaneously. However, this does not apply to JRuby and Rubinius interpreters.

Creating a Thread

As mentioned, we can work with threads using the Thread class. To create a new thread, call the thread.new method.

The syntax is:

Thread.new { # thread block goes here}

Ensure to include the code you want to have executed by the thread inside the pair of curly braces.

Here is an example:

Thread.new { puts "Hello, world!"}

Let us take a simple program that calculates the area of a circle.

def area
   pi = 3.14159
   rad = 7.3
   return (pi * rad * rad)
end
Thread.new {
   area()
   puts "Running inside the thread!"
}
puts "Execution complete!"

If you run the example above, you will notice that we do not get the area of the circle. This is because Ruby does not wait for the created threads to finish execution. To ensure the threads completes, we need to call the join method.

The join method will pause the main thread’s execution and wait for the threads specified in the join method to complete.

The following is the example code above with the join method implemented.

def area
   pi = 3.14159
   rad = 7.3
   return (pi * rad * rad)
end
thread = Thread.new {
   puts "The area of the circle is #{area()} cm2"
   puts "Running inside the thread!"
}
thread.join
puts "Execution complete!"

In this example, we get the output of the thread as shown below:

The area of the circle is 167.41533109999997 cm2
Running inside the thread!
Execution complete!

Terminating a Thread

Ruby provides various ways to terminate a thread. One such way is to use the kill method.

The syntax is:

Thread.kill(thread)

Specify the name of the thread to terminate inside the parenthesis.

Thread Exceptions

You will notice that if an exception comes up inside a thread, program execution does not stop.

For example:

def error_me
   raise "Error!"
end
Thread.new {error_me}
puts "I still run"

In the example above, we raise an exception inside the function passed to the thread. You will notice two things:

  1. The thread will not display the error message
  2. The code after the thread still runs. 

In some cases, you may want to stop execution if an exception comes up inside a thread. We can do this using the abort_on_execption.

For example:

Thread.abort_on_exception = true
thready = Thread.new do
   puts "I run before exception"
   raise "exception occurred!"
end
thready.join
puts "Sorry, I do not run!"

In the example above, the program will terminate if when an execption occurs inside the thread. Here is an example output:

I run before exception
#<Thread:0x000001fd13386960 threads.rb:2 run> terminated with exception (report_on_exception is true):
threads.rb:4:in `block in <main>': exception occurred! (RuntimeError)
threads.rb:4:in `
block in <main>': exception occurred! (RuntimeError)

Thread Variables

Variables created in a thread obey the Ruby scope rules. They are only accessible in the scope of the thread in which they are created.

Thread States

You can fetch the state of a given thread using the status method. You can also use the alive to check if the thread is running, and stop to check if the thread is dead.

There are five return values for the status method:

  1. Running – Returns run
  2. Sleep – returns sleeping
  3. Abort – Returns aborting
  4. Terminated with exception – returns nil
  5. Terminate normally – returns false.

Conclusion

In this guide, we discussed the basics of working with threads in the Ruby programming language.

It is good to note that there is more to it than what we have discussed in this guide. Consider the documentation to learn more.

Thank you for reading!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list