Open In App

Ruby | Introduction to Multi-threading

Last Updated : 18 Sep, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

Multi-threading is the most useful property of Ruby which allows concurrent programming of two or more parts of the program for maximizing the utilization of CPU. Each part of a program is called Thread. So, in other words, threads are lightweight processes within a process. An ordinary program contains single thread and all the statements or instructions are executed sequentially. But a multi-threaded program contains more than one thread and within each thread statements or instructions execute sequentially, but the thread itself executes concurrently on the multi-core processor. Multi-threading reduces the memory usage as compared to a single thread by performing multiple tasks. Before Ruby 1.9, threads were switched within the interpreter which are termed as Green Threads. But from Ruby 1.9 onwards, threading is performed by the operating system. The two threads running in the same Ruby application can never be truly concurrent. In Ruby, a multi-threaded program is created with the help of Thread class and a new thread is created by calling a block, i.e Thread.new.

Creating Threads in Ruby

In Ruby, creating a new thread is very easy. There are three blocks (Thread.new, Thread.start, or Thread.fork) by which you can create a thread in a program. Generally, Thread.new is used to create the thread. Once the thread created, the original thread will return from one of these Thread creation blocks and resume the execution with the next statement.

Syntax:

# Original thread is running

# creating thread
Thread.new
{
    # new thread runs here
}

# Outside the block
# Original thread is running

Example:




# Ruby program to illustrate 
# creation of threads
  
#!/usr/bin/ruby 
  
# first method
def Geeks1
   a = 0
   while a <= 3
  
       puts "Geeks1: #{a}"
  
      # to pause the execution of the current
      # thread for the specified time
      sleep(1)
  
      # incrementing the value of a
      a = a + 1
   end
  
end
  
# Second method
def Geeks2
   b = 0
  
   while b <= 3
  
       puts "Geeks2: #{b}"
  
      # to pause the execution of the current
      # thread for the specified time
      sleep(0.5)
  
      # incrementing the value of a
      b = b + 1
   end
  
end
  
# creating thread for first method
x = Thread.new{Geeks1()}
  
# creating thread for second method
y= Thread.new{Geeks2()}
  
# using Thread.join method to 
# wait for the first thread 
# to finish
x.join
  
# using Thread.join method to 
# wait for the second thread 
# to finish
y.join
  
  
puts "Process End"


Output:

Geeks1: 0
Geeks2: 0
Geeks2: 1
Geeks1: 1
Geeks2: 2
Geeks2: 3
Geeks1: 2
Geeks1: 3
Process End

Note: Output may be different as resources to threads are allocated by the operating system.


Terminating Threads

When a Ruby program is terminated, all the threads related to that program is also killed. A user can kill the threads using class ::kill.

Syntax:

Thread.kill(thread)

Thread variables and their Scope

As threads are defined by the blocks so they have access to local, global and instance variables which are defined in the scope of the block. Variables present in the block of the thread are the local variables for that thread and they are not accessed by any other thread block. Thread class allows a thread-local variable to be created and accessed by their name. If two or more threads wants to read and write the same variable concurrently then there must be thread synchronization.

Example:




# Ruby program to illustrate 
# Thread variables
   
#!/usr/bin/ruby 
  
# Global variable 
$str = "GeeksforGeeks" 
  
# first method
def Geeks1
  
   # only access by Geeks1 Thread
   a = 0
  
   while a <= 3
   
       puts "Geeks1: #{a}"
   
      # to pause the execution of the current
      # thread for the specified time
      sleep(1)
   
      # incrementing the value of a
      a = a + 1
  
  
   end
    
  # accessing str
  puts "Global variable: #$str"
  
end
   
# Second method
def Geeks2
  
   # only access by Geeks2 Thread
   b = 0
   
   while b <= 3
   
       puts "Geeks2: #{b}"
   
      # to pause the execution of the current
      # thread for the specified time
      sleep(0.5)
   
      # incrementing the value of a
      b = b + 1
   end
   
  # accessing str
  puts "Global variable: #$str"
  
end
   
# creating thread for first method
x = Thread.new{Geeks1()}
   
# creating thread for second method
y= Thread.new{Geeks2()}
   
# using Thread.join method to 
# wait for the first thread 
# to finish
x.join
   
# using Thread.join method to 
# wait for the second thread 
# to finish
y.join
   
   
puts "Process End"


Output:

Geeks1: 0
Geeks2: 0
Geeks2: 1
Geeks1: 1
Geeks2: 2
Geeks2: 3
Geeks1: 2
Global variable: GeeksforGeeks
Geeks1: 3
Global variable: GeeksforGeeks
Process End


Previous Article
Next Article

Similar Reads

Difference between Ruby and Ruby on Rails
1. Ruby : Ruby is an object-oriented scripting language launched in 1995 and is known as a general-purpose programming language. It was programmed in C programming language. Ruby is a secured programming language and its syntax is similar to Perl and Python. It was developed on the principle of user interface design and it is mainly used to develop
3 min read
Ruby Programming Language (Introduction)
Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid 1990’s in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby's development was to make it act as a sensible buffer between human program
4 min read
Ruby on Rails Introduction
Ruby on Rails or also known as rails is a server-side web application development framework that is written in the Ruby programming language, and it is developed by David Heinemeier Hansson under the MIT License. It supports MVC(model-view-controller) architecture that provides a default structure for database, web pages, and web services, it also
6 min read
Private Classes in Ruby
The concept of private, protected and public methods in Ruby is a bit different than it other languages like Java. In Ruby, it is all about which class the person is calling, as classes are objects in ruby. Private Class When a constant is declared private in Ruby, it means this constant can never be called with an explicit receiver, a private cons
3 min read
Ruby | Matrix cofactor() function
The cofactor() is an inbuilt method in Ruby returns the cofactor of the given index. Syntax: mat1.cofactor(i, j) Parameters: The function needs two index i and j, whose cofactor is to be returned. Return Value: It returns the cofactor of the given index. Example 1: # Ruby program for cofactor() method in Matrix # Include matrix require &quot;matrix
1 min read
Ruby Integer odd? function with example
The odd? function in Ruby returns a boolean value. It returns true if the number is odd, else it returns false. Syntax: number.odd? Parameter: The function takes the integer which is to be checked for odd or not. Return Value: The function returns a boolean value which determines if the value is odd or not. Example #1: # Ruby program of integer odd
1 min read
Ruby Integer div() function with example
The div() function in Ruby returns the integer division of two numbers. Syntax: (number1).div(number2) Parameter: The function needs two numbers number1 and number2, where number1 is the dividend and number2 is the divisor. Return Value: The function returns the integer division of two numbers. Example #1: # Ruby program of Integer div() function #
1 min read
Ruby | Symbol to_s function
Symbol#to_s() : to_s() is a Symbol class method which returns string representation of the symbol object. Syntax: Symbol.to_s() Parameter: Symbol values Return: string representation of the symbol object. Example #1 : # Ruby code for Symbol.to_s() method # declaring Symbol a = :aBcDeF # declaring Symbol b = :&quot;\u{e4 f6 fc}&quot; # declaring Sym
1 min read
Ruby | Set replace() function
The replace() is an inbuilt method in Ruby which replaces the contents of the set with the contents of the given enumerable object and returns self. Syntax: s1.replace(enum) Parameters: The function accepts an enumerable object which to be replaced in the set. Return Value: It returns the self object which contains the contents of the set after rep
1 min read
Ruby | Set reset() function
The reset() is an inbuilt method in Ruby resets the internal state after modification to existing elements and returns self. The elements will be reindexed and deduplicated. Syntax: s1.reset() Parameters: The function does not accepts any parameter. Return Value: It returns self . Example 1: # Ruby program to illustrate # the reset() method # requi
1 min read
Article Tags :