title: python + wsgi on a multi-threaded web-server: is this a race condition?
body: <p>Suppose that I've written a wsgi <code>application</code>. I run this application on <code>Apache2</code> on <code>Linux</code> with multi-threaded <code>mod-wsgi</code> configuration, so that my application is run in many threads per single process:</p>
  
  <pre><code>WSGIDaemonProcess mysite processes=3 threads=2 display-name=mod_wsgi
  WSGIProcessGroup mysite
  WSGIScriptAlias / /some/path/wsgi.py
  </code></pre>
  
  <p>The application code is:</p>
  
  <pre><code>def application(environ, start_response):
      from foo import racer
      status = '200 OK'
      response_headers = [('Content-type', 'text/plain')]
      start_response(status, response_headers)
      return [racer()] #call to racer creates a race condition?
  </code></pre>
  
  <p>module foo.py:</p>
  
  <pre><code>a = 1
  def racer():
      global a
      a = a + 1
      return str(a)
  </code></pre>
  
  <p>Did I just create a race condition with variable <code>a</code>? I guess, <code>a</code> is a module-level variable, that exists in <code>foo.py</code> and is the same (shared) among threads? </p>
  
  <p>More theoretical questions derived from this:</p>
  
  <ol>
  <li>Concurrent threads within the same process access and modify the same <code>a</code> variable so my example is not thread-safe?</li>
  <li>If my web-server is <code>Apache</code>, each thread of my application on Linux is created on C-level with <code>pthreads</code> API and the function, which the <code>pthread</code> must execute is some kind of python interpreter's main function? Or does Apache protect me somehow from this error?</li>
  <li>What if I were running this on a python-written web-server like <code>Tornado</code>'s <code>HTTPServer</code>? Web server, written in python, implements threads as python-level <code>threading.Thread</code> objects, and runs <code>application</code> function in each thread. So, I suppose it's a race condition? (I also suppose, in this case I can abstract from underlying C-level <code>pthreads</code> below <code>threading.Thread</code> implementation and worry only about python functions, because the interpreter won't allow me to modify C-level shared data and screw its functioning. So the only way to break thread-safety for me is to deal with global variables? Is that right?)</li>
  </ol>