Running threads inside my rails controller method Running threads inside my rails controller method ruby ruby

Running threads inside my rails controller method


It first depends if your calculations are doing processor heavy operations or are doing a lot blocking IO like reading from databases, the file system or the network. It wouldn't do much good if they're doing the former since each thread is taking up CPU time and no other thread can be scheduled - worse even if you're using Ruby MRI which has a Global Interpreter Lock. If the threads are doing blocking IO however, they can at least wait, let another thread run, wait, let another run and so on until they all return.

At the end you do have to join all the threads together because you want their return values. Do this below all your Thread.new calls. Save the return value of each Thread.new to an array:

threads = []threads << Thread.new ...

Then join them together before you render:

threads.each &:join

If you want to really be sure this helps you out just benchmark the entire action:

def show  start_time = Time.now.to_f  @stats = Stats.new  Thread.new {    @stats.top_brands = #RESULT OF FIRST CALCULATION       }  Thread.new {     @stats.top_colors = #RESULT OF FOURTH CALCULATION  }  @elapsed_time = Time.now.to_f - start_time  # do something with @elapsed_time, like putsing it or rendering it in your response  render json: @statsend

Hope that helps.