Jay Taylor | programmer notes

Jan/11

28

How to have threads exit with ctrl-c in Python

I found a great blog post on how to catch ctrl-c keyboard interrup signals within multi-threaded Python programs: http://www.regexprn.com/2010/05/killing-multithreaded-python-programs.html

#!/usr/bin/python

import os, sys, threading, time

class Worker(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)
    # A flag to notify the thread that it should finish up and exit
    self.kill_received = False

  def run(self):
      while not self.kill_received:
          self.do_something()

  def do_something(self):
      [i*i for i in range(10000)]
      time.sleep(1)

def main(args):

    threads = []
    for i in range(10):
        t = Worker()
        threads.append(t)
        t.start()

    while len(threads) > 0:
        try:
            # Join all threads using a timeout so it doesn't block
            # Filter out threads which have been joined or are None
            threads = [t.join(1) for t in threads if t is not None and t.isAlive()]
        except KeyboardInterrupt:
            print "Ctrl-c received! Sending kill to threads..."
            for t in threads:
                t.kill_received = True

if __name__ == '__main__':
  main(sys.argv)

Worked like a charm.

RSS Feed

No comments yet.

Leave a comment!

You must be logged in to post a comment.

<<

>>

Find it!