Python, threading and signals
Jan. 24th, 2008 07:10 pm
import threading
import signal
import time
keep_going = True
def handler(s, f):
global keep_going
keep_going = False
def worker():
global keep_going
while keep_going:
print "Working..."
time.sleep(1)
print "Done"
def main():
signal.signal(signal.SIGINT, handler)
for i in range(1):
t = threading.Thread(target=worker)
t.start()
for t in threading.enumerate():
if t != threading.currentThread():
t.join()
main()
However, this does not work as expected. Why? Because, when the main
thread issues the join() call, it sets a lock which
prevents the signal handler code from interrupting — something
that can be demonstrated by placing a sleep between the two loops.
The solution? Replace the blocking join loop with one that
times out, for example:
while True:
threads = threading.enumerate()
if len(threads) == 1: break
for t in threads:
if t != threading.currentThread():
t.join(1)
Which works for me...