[Web-SIG] WSGI thread affinity/interleaving

James Y Knight foom at fuhm.net
Sat Dec 17 22:50:05 CET 2005

So this came up when I was writing the twisted WSGI support, but at  
that point I just took the most conservative view and forgot to  
revisit the issue.

Take the following application:
def simple_wsgi_app(environ, start_response):
     start_response("200 OK")
     yield str(thread.get_ident())
     yield str(thread.get_ident())

Is there any guarantee that both times the iterator's .next() is  
called, they will be on the same thread?

d = {}
def simple_wsgi_app(environ, start_response):
     d[thread.get_ident()] = 0
     start_response("200 OK")
     yield "Start"
     assert d[thread.get_ident()] == 0
     d[thread.get_ident] += 1
     yield "Done"

Is there any guarantee that this will work? That is, is it possible  
that at the first "yield", another application will be allowed to  
run, in the same thread?

(Of course you'd probably actually want to use threading.local, not a  
dict of thread.get_ident, but, same idea.)

In Twisted, from the first entry to an application's code, until it's  
finished, it runs on the single thread, with nothing else running on  
that thread. This means that any app which is paused from generating  
too much output data for the client will be holding up a thread. When  
the app returns an iterator, Twisted could be running other requests  
on that thread while waiting for the client to read some data, if  
thread affinity is not required.


More information about the Web-SIG mailing list