# How to Implement Multithreading in Ruby

RubyServer Side ProgrammingProgramming

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.

#!/usr/bin/ruby

# first method
def First_Method
a = 0
while a <= 5

# 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

# Pause the execution of the current thread
sleep(0.5)

# incrementing the value of b
b = b + 1
end
end

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.

#!/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

# 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.join
y.join

puts "End"

## Output

On execution, it will produce the following output

Thread1: 0
End