4

According to the official python documentation, "finally" statement will always be executed, and thus is usually used for clean-up operations.

If "finally" is present, it specifies a ‘cleanup’ handler. The "try" clause is executed, including any "except" and "else" clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The "finally" clause is executed. If there is a saved exception, it is re-raised at the end of the "finally" clause. If the "finally" clause raises another exception or executes a return or break statement, the saved exception is discarded:

However, when I implemented the "try-finally" statement in a thread, "finally" part seems not being executed.

from __future__ import print_function
import threading
def thread1():
    try:
        while True:
            pass
    except:
        print("exception")
    finally:
        print("closed")

t = threading.Thread(target = thread1)
t.setDaemon(True)
t.start()
while True:
    pass

When interrupted by ctrl-c, "closed" is not printed on the screen. Why is that?

While in following code "finally" does work (no surprise)

from __future__ import print_function
try:
    while True:
       pass
finally:
    print("closed")
Charlie Lam
  • 111
  • 7

2 Answers2

4

In the documentation for the thread module (which underlies threading):

When the main thread exits, it is system defined whether the other threads survive. On SGI IRIX using the native thread implementation, they survive. On most other systems, they are killed without executing try ... finally clauses or executing object destructors.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Intercept signal.SIGINT in the main thread and from its handler send all child threads message to clean-up and stop. The simplest way would be a shared global variable that child threads check in their main loop. – void Feb 17 '17 at 07:07
  • 1
    What if the child threads are blocking waiting on input (e.g. from the network). – user48956 Sep 19 '17 at 01:24
-1

CTRL+C kills the script, i.e. it stops running and nothing else will process.

jylny
  • 146
  • 1
  • 1
  • 8
  • 1
    This doesn't answer the question. Also, it isn't true; you can catch a KeyboardInterrupt and continue processing. – Will Vousden Feb 17 '17 at 09:14