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.
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).