How to Implement Multithreading in Ruby



In this article, we will learn how we can use multithreading in Ruby. We will take a couple of examples, where we will spawn two new threads and then perform some concurrent operations on them. In Ruby, we can create a new thread with the help of the Thread.new() function.

Example 1

Take a look at the following example to understand the nature of multiple threads and how they are executed in Ruby.

Open Compiler
#!/usr/bin/ruby # first method def First_Method a = 0 while a <= 5 puts "Thread1: #{a}" # pause the execution of the current thread sleep(1) # incrementing the value of a a = a + 1 end end # Second method def Second_Method b = 0 while b <= 3 puts "Thread2: #{b}" # Pause the execution of the current thread sleep(0.5) # incrementing the value of b b = b + 1 end end x = Thread.new{First_Method()} y = Thread.new{Second_Method()} # using Thread.join x.join y.join puts "End"

Output

On execution, it will produce the following output

Tuts1: 0
Tuts2: 0
Tuts2: 1
Tuts1: 1
Tuts2: 2
Tuts2: 3
Tuts1: 2
Tuts1: 3
Tuts1: 4
Tuts1: 5
End

In this example, we looked at two threads and how context switching is happening between them.

Example 2

Now let's take a look at how we can define some logs in between the functions to show the scope of the threads. Consider the code shown below.

Open Compiler
#!/usr/bin/ruby $str = "Learn To Code in Ruby" # first method def First_Method a = 0 while a <= 5 puts "Thread1: #{a}" # pause the execution of the current thread sleep(1) # incrementing the value of a a = a + 1 end puts "Global variable: #$str" end # Second method def Second_Method b = 0 while b <= 3 puts "Thread2: #{b}" # pause the execution of the current thread sleep(0.5) # incrementing the value of b b = b + 1 end puts "Global variable: #$str" end x = Thread.new{First_Method()} y = Thread.new{Second_Method()} # using Thread.join x.join y.join puts "End"

Output

On execution, it will produce the following output

Thread1: 0
Thread2: 0
Thread2: 1
Thread1: 1
Thread2: 2
Thread2: 3
Thread1: 2
Global variable: Learn To Code in Ruby
Thread1: 3
Thread1: 4
Thread1: 5
Global variable: Learn To Code in Ruby
End
Updated on: 2022-04-12T13:27:24+05:30

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements