try finally doesn't

Jeff Epler jepler at
Fri Nov 28 20:00:52 CET 2003

The interaction of signals, threads and exiting is pretty minimal in
Python.  I think that in this case a KeyboardInterrupt is delivered to
the main thread, and when it's uncaught it exits the program, closing
all threads.

Python doesn't even have the capability of delivering an exception to an
arbitrary thread, and that would go double for native code with no GIL.

You'll have to write your code more like this:

exiting = 0
active_threads = 0

def x():
	global active_threads
	active_threads += 1
	for i in range(60):
		if exiting:
			active_threads -= 1

t = thread.start_new_thread(x, ())

	exiting = 1
	while active_threads:

... except that you'd want to make active_threads into something that
doesn't suffer from race conditions.

PS code untested, and you should consider using the threading module
anyway, if you've decided you must use threads to get the job done.

More information about the Python-list mailing list