hellomello
hellomello

Reputation: 8597

Ruby: Issues running multiple threads?

Is there something wrong with running multiple threads?

When I load the page using action1, it works.

HomeController

def action1
    threads = []
    threads << Thread.new {@lub = client.tag_recent_media('tag1')}
    Thread.new{@tags = client.tag_recent_media('encorebeach')}
    Thread.new{@location = client.location_recent_media('16565')}

    threads.each(&:join)  
end

Home View

<% (@lub+@tags+@location).each do |media| %>
<%= media %>
<% end %>

Here's another controller with a different view

AnotherController

def action1
    threads2 = []
    threads2 << Thread.new {@lub2 = client.tag_recent_media('tag1')}
    Thread.new{@tags2 = client.tag_recent_media('encorebeach')}
    Thread.new{@location2 = client.location_recent_media('16565')}

    threads2.each(&:join)  
end

Another View

<% (@lub2+@tags2+@location2).each do |media| %>
<%= media %>
<% end %>

For the second output I get an error

undefined method `+' for nil:NilClass

I think it is something wrong with the threads. Can someone assist me as to why this is happening? Is it because I already executed a thread in the home page, and then when I want to go to another page, it runs a thread again and it won't work?

Thanks!

Upvotes: 0

Views: 136

Answers (1)

clacke
clacke

Reputation: 8066

threads only contains your first thread. It is by pure luck that your first method has its threads finish before you use the instance variables in the view.

threads = []
threads << Thread.new {@lub = client.tag_recent_media('tag1')}
threads << Thread.new{@tags = client.tag_recent_media('encorebeach')}
threads << Thread.new{@location = client.location_recent_media('16565')}

or even simpler:

threads = [
  Thread.new{@lub = client.tag_recent_media('tag1')},
  Thread.new{@tags = client.tag_recent_media('encorebeach')},
  Thread.new{@location = client.location_recent_media('16565')}
]

will accomplish what you want.

It is quite likely that you will not gain much performance from this compared to just running them in the controller thread. It is even possible that you will thrash the database server, slowing it down instead. Do measure whether the threads buy you any performance, and keep in mind that there are many pitfalls when using threads.

Upvotes: 2

Related Questions