I''m using #defer to run database calls in, and during one request there are 2 queries on average, sometimes 3-4. Basically once the client connects and sends a request, I instantiate a class which handles that type of request. Right now I have #defer sprinkled throughout the code whenever I call the database. I''m wondering if it would be better to just wrap the whole thing in one thread? Would make the code a bit cleaner and easier. Chris
Francis Cianfrocca
2006-Aug-21 04:42 UTC
[Eventmachine-talk] best approach when using threads
On 8/21/06, snacktime <snacktime at gmail.com> wrote:> I''m using #defer to run database calls in, and during one request > there are 2 queries on average, sometimes 3-4. Basically once the > client connects and sends a request, I instantiate a class which > handles that type of request. Right now I have #defer sprinkled > throughout the code whenever I call the database. I''m wondering if it > would be better to just wrap the whole thing in one thread? Would > make the code a bit cleaner and easier. > > Chris > _______________________________________________ > Eventmachine-talk mailing list > Eventmachine-talk at rubyforge.org > http://rubyforge.org/mailman/listinfo/eventmachine-talk >Chris, I think the cleanest model would be to call #defer once, to kick off a logical operation (or "transaction" if you will) on behalf of a single waiting network client or server. And the block you pass to defer can have any number of locally-blocking DB calls in it. You don''t gain extra by deferring each of the individual database calls, because you can''t continue the work on behalf of the associated network connection until they''re all done anyway. Meanwhile, the network i/o will still continue on your program''s main thread (which runs the EM loop), and database activity for other network connections will simultaneously continue on other #defer threads. Does that make sense? I think this is what you meant by "wrap the whole thing in one thread." And I''m still thinking about how best to turn the #defer thread pool into a database connection pool. I''m thinking of adding a new call (perhaps EventMachine#set_deferred_init) that would be run once for each connection pool thread, that would set up per-thread data that could be anything you want (like a DB connection).