title: Python - Polling a variable
body: <p>I change a global variable in a signal handler and poll for it in the main program. But the value does not change in the main thread.</p>
  
  <p>Is there a qualifier that I need to use to make it a volatile (like in Java) variable?</p>
  
  <p>Here's the program:</p>
  
  <p><strong>test.py</strong></p>
  
  <pre><code>import time
  import signal
  
  def debug():
      closeSession = False
  
      def sigint_handler(signal, frame):
          global closeSession
  
          print('Breaking the poll...')
          closeSession=True
  
      signal.signal(signal.SIGINT, sigint_handler)
  
      # Start a program...
  
      while not closeSession:
          time.sleep(1)
          print('Polling... closeSession = %r' % closeSession)
  
      print('Exiting! Bye.')
      # Sent 'quit' to stdin of the program
  
  if __name__ == "__main__":
      debug()
  </code></pre>
  
  <p><code>sigint_handler()</code> gets called whenever I press <kbd>Ctrl</kbd> + <kbd>C</kbd> but the new value of <code>closeSession</code> is not used in the main thread.</p>
  
  <p>I get the following output:</p>
  
  <blockquote>
    <p>$ python test.py<BR> Polling... closeSession = False<BR> Polling...
    closeSession = False<BR></p>
  </blockquote>
  
  <p><em>I press <kbd>Ctrl</kbd> + <kbd>C</kbd></em></p>
  
  <blockquote>
    <p>^CBreaking the poll...<BR> Polling... closeSession = False<BR></p>
  </blockquote>
  
  <p><em>Press <kbd>Ctrl</kbd> + <kbd>C</kbd>, again</em></p>
  
  <blockquote>
    <p>^CBreaking the poll...<BR> Polling... closeSession = False<BR></p>
  </blockquote>
  
  <p><em>Press <kbd>Ctrl</kbd> + <kbd>C</kbd>, again</em></p>
  
  <blockquote>
    <p>^CBreaking the poll...<BR> Polling... closeSession = False<BR>
    Polling... closeSession = False</p>
  </blockquote>