Topic: Threading in Controllers

I'm tracking web statistics in my application through a database table.  I have my reasons so don't go asking why I'm not using the apache log or whatever wink  The obvious side effect is that there's a database insert for every action thats called.  My thought was to spawn a new thread for these inserts so they would be asynchronous. 

So I did some reading on threads, and my only question is about how threads are terminated based on the execution of the controller.  According to Programming Ruby "When a Ruby program terminates, all running threads are killed, regardless of their states. However, you can wait for a particular thread to finish by calling that thread's  Thread#join   method."

Does this mean that if I spawn a thread within the controller, and the thread takes longer to run than the controller, it will be prematurely terminated?  If so, would the join method screw up the flow of the controller?

Re: Threading in Controllers

I'd be extremely careful if you want to tackle multithreading with Rails because many parts are not thread safe. See this article for some details. I don't really know enough about it to help you any further. sad

Railscasts - Free Ruby on Rails Screencasts

Re: Threading in Controllers

I figured somebody would say that.

Re: Threading in Controllers

Ryan, what that article says to me is that running rails under multiple threads is bad, not necessarily that running thread within rails is bad.  I'm still skeptical though.

Re: Threading in Controllers

Sounds like you might wanna use something like background drb for your tasks instead of actually enabling threads in rails.

http://backgroundrb.rubyforge.org/

Re: Threading in Controllers

That looks really cool, but I think it would be overkill for my purposes.

Re: Threading in Controllers

I was thinking about this just a couple nights ago.  I wonder if an after_filter on your controllers that commits a cached set of operations would be sufficient.  If I'm not mistaken isn't the output sent to the browser before after_filter is run?

Re: Threading in Controllers

Ah, good point.  That would be cool, cause thats what I'm already doing anyway.  I'll look into that some more.