Alex
Alex

Reputation: 61

How to make this rails app multithreaded?

I would like to ask advice in my little problem. This is my class, this is my controller. I want to make this application multithreaded. Tell me please, which path would be best? The controller's fast hack does not solve the problem:

 if params[:select].present?
            threads = []
        params[:select].each do |item|
        threads << Thread.new {
           tweet = current_user.tweet.detect {
            |t| item == t.name
        } 

           config = {
.....
etc

}
end
threads.each(&:join)

It does not work, the process stops immediately:

Started GET "/tweets?select%5B%5D=adamasmit&select_action=follow&tag=&tag1=" for 127.0.0.1 at 2019-03-06 01:37:28 +0300
Processing by TweetsController#index as */*
  Parameters: {"select"=>["adamasmit"], "select_action"=>"follow", "tag"=>"", "tag1"=>""}
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 11], ["LIMIT", 1]]
  Tweet Load (0.6ms)  SELECT "tweets".* FROM "tweets" WHERE "tweets"."user_id" = ?  [["user_id", 11]]

and that is all.

This is an example of the normal operation of the application:

  Started GET "/tweets?select=adamasmit&select_action=unfollow&tag=&tag1=" for 127.0.0.1 at 2019-03-06 18:17:43 +0300
Processing by TweetsController#index as */*
  Parameters: {"select"=>"adamasmit", "select_action"=>"unfollow", "tag"=>"", "tag1"=>""}
  User Load (1.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 11], ["LIMIT", 1]]
  Tweet Load (0.3ms)  SELECT "tweets".* FROM "tweets" WHERE "tweets"."user_id" = ?  [["user_id", 11]]
adding follower to an array: cmirnow
adding follower to an array: travel_slovenia
adding follower to an array: godraksha
.....
etc
adding follower to an array: Pkakooza
adding follower to an array: chrissycrew3
adding friend to an array: cmirnow
adding friend to an array: travel_slovenia
adding friend to an array: godraksha
.....
etc
adding friend to an array: Pkakooza
adding friend to an array: chrissycrew3
adding friend to an array: RivaresF
follow: RivaresF
  Rendering tweets/index.html.erb within layouts/application
  Rendered tweets/index.html.erb within layouts/application (3.7ms)
Completed 200 OK in 3311ms (Views: 132.1ms | ActiveRecord: 2.6ms)


   (0.1ms)  begin transaction
   (0.1ms)  commit transaction

What do you advise?

Upvotes: 0

Views: 36

Answers (1)

phoet
phoet

Reputation: 18845

the rails way would be to use ActiveJob to perform such expensive operations in the background: https://guides.rubyonrails.org/active_job_basics.html

Upvotes: 2

Related Questions