Multithreading in Ruby Language

Multithreading in Ruby Language

Multithreading is a powerful technique in computer programming that allows a program to execute multiple threads concurrently. This capability can significantly improve the performanc

e of applications, making them more responsive and efficient. In this article, we’ll explore how multithreading works in the Ruby programming language and provide examples to illustrate its practical use.

What is Multithreading?

Multithreading is the ability of a program to execute multiple threads concurrently. Threads are lightweight sub-processes that share the same memory space and can perform tasks independently. By using multithreading, you can take advantage of the available CPU cores, potentially speeding up your application’s performance.

Ruby, a dynamic and object-oriented programming language, supports multithreading through its Thread class. Let’s dive into some practical examples to see how you can use multithreading in Ruby.

Basic Multithreading Example

Here’s a simple example of multithreading in Ruby, where we create two threads that execute different tasks simultaneously:

# Define a thread that prints numbers from 1 to 5
thread1 = Thread.new do
  1.upto(5) do |i|
    puts "Thread 1: #{i}"
    sleep(1)
  end
end

# Define another thread that prints letters A to E
thread2 = Thread.new do
  ('A'..'E').each do |letter|
    puts "Thread 2: #{letter}"
    sleep(1)
  end
end

# Wait for both threads to finish
thread1.join
thread2.join

puts "Main thread has finished."

In this example, Thread.new is used to create two separate threads that execute their tasks concurrently. The join method is used to wait for the threads to complete before continuing with the main thread.

Sharing Data Between Threads

One important aspect of multithreading is data sharing among threads. Since threads share the same memory space, it’s essential to be cautious when multiple threads access the same variables. Ruby provides the Mutex class for thread synchronization. Here’s an example:

# Create a Mutex object
mutex = Mutex.new

# Shared counter
counter = 0

# Create two threads that increment the counter
thread1 = Thread.new do
  10.times do
    mutex.synchronize do
      counter += 1
    end
  end
end

thread2 = Thread.new do
  10.times do
    mutex.synchronize do
      counter += 1
    end
  end
end

# Wait for both threads to finish
thread1.join
thread2.join

puts "Final counter value: #{counter}"

In this example, a Mutex is used to ensure that only one thread at a time can modify the counter variable, preventing data corruption due to concurrent access.


Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading