» Quick Introduction to Ruby » 2. Advanced » 2.5 Threads

Threads

Threading can be implemented using the Thread class.

Basic Thread Creation

# Creating and running two threads
thread1 = Thread.new { puts "Thread 1 running" }
thread2 = Thread.new { puts "Thread 2 running" }

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

puts "Main thread exiting"

Passing Parameters to Threads

# Creating and running a thread with parameters
thread = Thread.new("Hello", "Literank") do |greeting, target|
  puts "#{greeting}, #{target}!"
end

# Wait for the thread to finish
thread.join

puts "Main thread exiting"

Synchronization with Mutex

# Using Mutex for synchronization
counter = 0
mutex = Mutex.new

# Function to increment counter safely
def increment_counter(mutex, counter)
  1000.times do
    mutex.synchronize do
      counter += 1
    end
  end
  counter
end

# Creating and running two threads that increment the counter
thread1 = Thread.new { counter = increment_counter(mutex, counter) }
thread2 = Thread.new { counter = increment_counter(mutex, counter) }

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

puts "Counter value: #{counter}"
puts "Main thread exiting"

Thread Pool

# Using a thread pool for parallel execution
pool_size = 3
tasks = Queue.new

# Enqueue tasks
10.times { |i| tasks << i }

# Worker function
def worker(tasks)
  until tasks.empty?
    task = tasks.pop(true) rescue nil
    if task
      puts "Task #{task} processed by thread #{Thread.current.object_id}"
      sleep(0.3) # Simulate some work
    end
  end
end

# Create and run threads in a pool
threads = Array.new(pool_size) do
  Thread.new { worker(tasks) }
end

# Wait for all threads to finish
threads.each(&:join)

puts "Main thread exiting"

Code Challenge

Write a Ruby program that calculates the sum of elements in an array using multiple threads.

  1. Define a function parallel_sum(array, num_threads) that takes an array of integers and the number of threads to use. The function should return the sum of all elements in the array.
  2. Use Ruby's Thread class to create multiple threads for parallel processing. Each thread should be responsible for summing a portion of the array.
Loading...
> code result goes here
Prev
Next