# Threading, returning from action method, blocking

**URL:** <https://www.ruby-forum.com/t/threading-returning-from-action-method-blocking/159909>\
**Category:** Rails\
**Created:** [February 9, 2009, 11:40pm UTC](https://www.ruby-forum.com/t/threading-returning-from-action-method-blocking/159909 "2009-02-09T23:40:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jrochkind](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/779978/32.png) [@jrochkind](https://www.ruby-forum.com/u/jrochkind)\
**Post date:** [February 9, 2009, 11:40pm UTC](https://www.ruby-forum.com/t/threading-returning-from-action-method-blocking/159909/1 "2009-02-09T23:40:17Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![jrochkind](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/779978/32.png) [@jrochkind](https://www.ruby-forum.com/u/jrochkind)\
**Post date:** [February 10, 2009, 5:19am UTC](https://www.ruby-forum.com/t/threading-returning-from-action-method-blocking/159909/2 "2009-02-10T05:19:32Z")

</div>

I would give the spawn plugin a try.

[http://rubyforge.org/projects/spawn/](http://rubyforge.org/projects/spawn/)

spawn do  
do\_stuff # stuff takes a long time  
end
