Sid
Sid

Reputation: 4987

Ruby/Rails Multithreading - Run statements in Parallel (preferably using Parallel Gem)

In my RoR application (Ruby 2.0.0, Rails 4.0), I have a set of statements:

a = user.get_some_data
b = car.get_car_parts
c = home.get_temperature
d = random.get_random_data

aggregated = a + b + c + d 

As deliberately shown above, the execution that assigns values to variables a, b, c and d are independent and happen in any order, or in parallel. I have Parallel Gem in my Gemfile so this should be easy, however it does not seem to support non collection statements pretty well. Any way I can parralelize the statements and wait for execution at aggregated variable to get all the data?

Upvotes: 2

Views: 810

Answers (1)

user000001
user000001

Reputation: 33307

Since you say you want to avoid using a collection, you could use a case statement to assign the variables.

a = b = c = d = 0
Parallel.each 1..4, in_threads: 4 do |j|
  puts "running thread #{j}..."
  case j
    when 1
      a = user.get_some_data
    when 2
      b = car.get_car_parts
    when 3
      c = home.get_temperature
    when 4
      d = random.get_random_data
  end
end
puts "done. a=#{a}, b=#{b}, c=#{c}, d=#{d}"
aggregated = a + b + c + d 
puts "aggregated: #{aggregated}"

A slightly briefer but less readable IMO option would be to use procs inside an array:

aggregated = Parallel.map([
  ->(){ user.get_some_data },
  ->(){ car.get_car_parts },
  ->(){ home.get_temperature },
  ->(){ random.get_random_data }
], in_threads: 4){|j| j.call}.reduce(:+)

Upvotes: 2

Related Questions