Y
Y
Yaschik2015-11-20 02:34:06
Ruby on Rails
Yaschik, 2015-11-20 02:34:06

Multithreading and long polling in Ruby on Rails, why does the main thread sleep?

There is this code in the controller:

def game
    ddos=Time.now
    result=nil
    r=Thread.new do
      while true
        sleep 1 //Latency-like-defend-of-DB
        result = Model.where('id!=?',1).last //Requests any model, as example
        if result
          break
        end
      end
    end
    while true
      if ddos+30<Time.now //If server not respond after 30 sec
        result='Too long'
      end
      if result
        r.kill // Kill thread
        break
      end
    end
    render json:{result:result}
  end

Google did not give anything good, I'm still weakly familiar with rails.
With this implementation, the main thread goes to sleep and the server does not respond to other connections.
ruby - 2.2.2, rails - 4.2.1.
Tried webrick and puma.
Both work with the same connection, the question arose - I'm doing something wrong, but how to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
raventid, 2015-11-20
@raventid

As far as I understand you are just trying to set a time limit for a query to the database. You can set a timeout of 30 seconds in the Rails config :) See here . It will also be possible to catch the timeout exception and render the error code and message. I don't see much point in creating a thread. By the way, look at how ActiveRecord and its pool work , it can do a lot of things, including with the participation of threads.
Yes, webrick is also a single-threaded guy and it’s better not to torture him, install thin for development.
PS I tried to rewrite your method a little and run it without rails - everything works, and in general it's logical :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question