tags:

views:

30

answers:

1

I have a connection to an external resource that I need to make for my Pylons app (think along the lines of a database connection.) There is a modest amount of overhead involved in establishing the connection.

I could setup a piece of middleware that opens and closes the connection with every request but that seems wasteful. I'd like to establish a connection for each new thread that starts up and save myself the overhead. How do I hook into thread startup in Pylons?

+1  A: 

Do the connections have to belong to a single thread for their lifetime?

If not, you could consider implementing your own connection pool for this resource. The pool would be responsible for initializing connections and each thread would acquire and release the connections as they are needed.

If you want to limit the number of available connections, you just block during the acquire phase until a connection is released or some timeout is reached.

The code to implement such a pool is going to be very dependent on the resource you are talking about, so it would be difficult to give you anything other than a suggested API.

Joe Holloway
No, they don't have to belong to the same thread, now that I think about it, as long as they are consistent for the duration of a request. As long as I have num_connections >= num_threads, I'd be OK. Any idea how to get the number of threads running?
dave mankoff
Actually - I could just have my acquire method create new connections on demand, up to some limit. I will investigate this, thanks!
dave mankoff
I don't think Pylons controls that, but is determined by whatever is hosting your WSGI container, be it Apache/mod_wsgi or other, so not sure if there is a 'portable' way to do it. However, if you design the connection pool correctly, your application would function properly for any num_connections >= 1 regardless of num_threads. Each thread would just block until a connection became available. (Making a couple of assumptions there, but generally speaking)Then it would just be a matter of finding the sweet spot where you have enough connections in the pool to ensure minimal blocking.
Joe Holloway