title: Global dict, not all threads adding keys to it?
body: <p>I am confused about global variables in Python. Sometimes a global variable is shared among all instances of my program and sometimes an instance will create its own version of the global variable.</p>
  
  <p>What I need is to have one handler that handles items put into a global dictionary. There is only one function that adds items to the global dictionary, but this function is run multiple times concurrently.</p>
  
  <p>In views:</p>
  
  <pre><code>global_dict = {}
  
  def handler():
      global global_dict 
  
      print "Starting handler"
      while True:
          local_dict = dict(global_dict) 
          for key, v in local_dict.iteritems():
              handle_the_item(v)
              del global_dict[key]
              print "Handled: ", key
          time.sleep(0.05)
  
  def some_function(function_number)
      global global_dict
  
      print "Starting function", function_number
      for x in y:
          key = random.randint(0, 5000000)
          print function_number, "giving to handler:", key
          global_dict[key] = some_item
  </code></pre>
  
  <p>I start:</p>
  
  <p>(I use Django so each function is started by calling a url with some parameter)</p>
  
  <pre><code>handler()
  some_function(1)
  some_function(2)
  some_function(3)
  </code></pre>
  
  <p>It prints:</p>
  
  <pre><code>Starting handler
  Starting function 1
  Starting function 2
  Starting function 3
  
  1 giving to handler 111111
  2 giving to handler 222222
  3 giving to handler 333333
  1 giving to handler 444444
  2 giving to handler 555555
  3 giving to handler 666666
  
  Handled: 111111
  Handled: 222222
  Handled: 444444
  Handled: 555555
  </code></pre>
  
  <p>The handler never handles the items added by function 3. As far as I can tell, this is because the handler and function 3 each have their own instances of the (supposedly) global variable global_dict. I also verified this by printing out the length of global_dict in some_function(). global_dict in function 3 keeps growing as more items are added.</p>
  
  <p>Note that it is random which functions share an instance of global_dict and which have their own. If I stop everything and run it again, it may be that all instances share global_dict. Or none. Or 3 and 1 along with the handler.</p>