A Question About Handling SIGINT With Threads

Keith vetter at lincom-asg.com
Wed Apr 13 11:12:05 EDT 2005


I got this to work, but was hoping there was a better way.  I was
hoping that I wouldn't have to use globals.  I wouldn't doubt that I
could be totally off in what I am doing.

Here is some psuedo-code of what I did:

def main_thread():
      # Don't know how to get rid of these guys
      global lock
      global my_thread

      # Set up a signal handler for Ctrl-C
      signal.signal(signal.SIGINT, sighdlr)

      # Create & start thread
      lock = thread.allocate_lock()
      lock.acquire()
      my_thread = threading.Thread(
                              target=child_thread,
                              name='thread_test',
                              args=(lock,)
      my_thread.start()

      do_some_work_here()

      # Tell thread to stop working
      lock.release()

      # Wait for child thread to finish
      my_thread.join()

def child_thread(lock):

      while lock.locked():
              do_some_stuff()

      do_some_cleanup()

def sighdlr(signum, frame):

      # Allow child to finish
      lock.release()
      my_thread.join()
      sys.exit(1)




More information about the Python-list mailing list