Home »
Ruby programming
Threads in Ruby
Ruby threads: Here, we are going to learn about the threading in Ruby programming language with examples.
Submitted by Hrithik Chandra Prasad, on October 02, 2019
Ruby Threads
In Ruby, with the help of threads, you can implement more than one process at the same time or it can be said that Thread supports concurrent programming model. Apart from the main thread, you can create your thread with the help of the "new" keyword. Threads are light in weight and you can create your thread with the help of the following syntax:
Thread_name = Thread.new{#statement}
Now, let us see how we can create a thread in Ruby with the help of a supporting example?
=begin
Ruby program to demonstrate threads
=end
thr = Thread.new{puts "Hello! Message from Includehelp"}
thr.join
Output
Hello! Message from Includehelp
In the above example, we have created a thread named as thr. Thr is an instance of Thread class and inside the thread body, we are calling puts method with the string. thr.join method is used to start the execution of the thread.
Now, let us create a user-defined method and call it inside the thread in the following way,
=begin
Ruby program to demonstrate threads
=end
def Includehelp1
a = 0
while a <= 10
puts "Thread execution: #{a}"
sleep(1)
a = a + 1
end
end
x = Thread.new{Includehelp1()}
x.join
Output
Thread execution: 0
Thread execution: 1
Thread execution: 2
Thread execution: 3
Thread execution: 4
Thread execution: 5
Thread execution: 6
Thread execution: 7
Thread execution: 8
Thread execution: 9
Thread execution: 10
In the above code, we are creating an instance of Thread class names as x. Inside the thread body, we are giving a call to the user-defined method Includehelp1. We are printing the loop variable for 10 times. Inside the loop, we have accommodated the sleep method which is halting the execution for 1 second. We are starting the execution of thread with the help of the join method.
=begin
Ruby program to demonstrate threads
=end
def myname
for i in 1...10
p = rand(0..90)
puts "My name is Vaibhav #{p}"
sleep(2)
end
end
x = Thread.new{myname()}
x.join
Output
My name is Vaibhav 11
My name is Vaibhav 78
My name is Vaibhav 23
My name is Vaibhav 24
My name is Vaibhav 82
My name is Vaibhav 10
My name is Vaibhav 49
My name is Vaibhav 23
My name is Vaibhav 52
In the above code, we have made a thread and printing some values inside it. We are taking help from the rand method and sleep method.
By the end of this tutorial, you must have understood the use of thread class and how we create its objects.