Is Ruby Single Threaded

MD Aminul Islam Jan 05, 2023
  1. What Is Threading
  2. Is Ruby Single-Threaded or Multi-Threaded
  3. an Example of a Ruby Multi-Threading Program
Is Ruby Single Threaded

Multi-threading is an important topic in modern programming languages. But we must run a program in a single thread for other purposes.

This article will discuss threading in Ruby, along with some examples and explanations.

What Is Threading

A thread is a block of codes and commands that execute on the CPU sequentially. It is a lightweight process that runs on the CPU.

If multiple threads exist on your program, they can share the same resources, like variables and methods. Threading makes efficient use of the CPU and provides faster execution.

Is Ruby Single-Threaded or Multi-Threaded

Yes, Ruby supports Multi-threading. It allows you to create concurrent programming of two or more parts (thread) for using the CPU efficiently.

If you program in Ruby with a single thread, it will execute through one core of the CPU, so if your CPU is quad-core, then the other three cores will not be involved in executing your program.

So the program without threading or a single thread is slower than a multithread program. That’s why single-thread programs are not recommended in modern programming.

Besides, a web application performs more than one task simultaneously. So it is very hard to design a web application using a single thread.

an Example of a Ruby Multi-Threading Program

In our example below, we will illustrate how we can use multithread in a Ruby program. Have a look at the below example code.

def ThreadOne
   a = 0
   while a <= 3
      puts "Thread One"
      # Pause the execution
      sleep(1)
      # incrementing the value of b
      a = a + 1
   end
end

def ThreadTwo
   b = 0
   while b <= 3
       puts "Thread Two"
      # Pause the execution
      sleep(1)
      # incrementing the value of b
      b = b + 1
   end

end

# Creating thread with "ThreadOne()"
t1 = Thread.new{ThreadOne()}

# Creating thread with "ThreadTwo()"
t2= Thread.new{ThreadTwo()}

# wait until the first thread complete
t1.join

# wait until the second thread complete
t2.join

  puts "Process execution has been done!!!"

The purpose of each line is already left as comments. After running the above Ruby program, you will get the below output in your console.

Thread One
Thread Two
Thread One
Thread Two
Thread One
Thread Two
Thread One
Thread Two
Process execution has been done!!!
MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn