Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question