Forum: Ruby on Rails threading, returning from action method, blocking

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0f50b9a2ad85666d537d39bda49327ee?d=identicon&s=25 Jonathan Rochkind (jrochkind)
on 2009-02-09 23:40
So, in a Rails 2.1 app, I'm doing a bit of threading. Even though this
isn't exactly recommended, it seemed to work (taking care to use
ActiveRecord in a thread-safe manner, or not at all in threads).

But I've noticed something odd.

The main thing I do with a thread, is in an action method (ie, an action
in a controller), right before returning from the method, I start a
thread to do some finishing up clean-up in the background. Since this
cleanup is potentially a lengthy process, the idea is that this won't
prevent the response from returning to the browser.

def someAction
  # some stuff

  Thread.new do
    #background(?) stuff
  end

  return
end

The expectation was that the response would be returned to the browser
immediately, it would not wait for that Thread to execute. It wouldn't
matter how long the code in "#background(?) stuff" took to run, the
Thread would be started, and then the next statement would be read after
the thread, ending the action method, proceeding with the view, without
waiting on the Thread. Everything could be asynchronous.

However, I've recently noticed that this doesn't seem to be the case.
The stuff in the Thread _is_ keeping the response from being returned.
If I put a "sleep(10)" at the top of the Thread do body, then everything
clears up--it doesn't wait an extra 10 seconds for teh response, THEN
the response is returned immediately. But without this, it seems that
something in the Thread is blocking the rest of the Rails process to
return the response, not for the entire time it takes it to run, but...
for some time.

Does anyone have any ideas what's going on, or how else to accomplish
this? (Please don't same BackgrounDRB).

Thanks,

Jonathan
47c3af2d56d44eb1d08a601c837a1262?d=identicon&s=25 alberto (Guest)
on 2009-02-10 05:19
(Received via mailing list)
I would give the spawn plugin a try.

http://rubyforge.org/projects/spawn/

spawn do
    do_stuff  # stuff takes a long time
end
This topic is locked and can not be replied to.