Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's sys.exit behavior when a non-daemon thread is waiting indefinitely on a lock

I am relatively new to Python and would like to understand the behavior of sys.exit() in the following case.

Main thread calls a sys.exit() but there's another non-daemon thread which was already waiting on some lock indefinitely.

I have tested this in my program and looks like the program as a whole doesn't exit. Is this expected? I am not sure if the non-daemon thread is handling SystemExit exception since that's in a third-party library.

Thanks in advance for the help.

like image 465
Buchi Avatar asked Apr 10 '12 08:04

Buchi


1 Answers

For threads created with the threading module, the main thread joins all non-daemon threads on exit. You can see this in threading.py by searching for exitfunc (verified in Python 2.4.5, 2.7.2, and 3.2.2 source)

If you have some non-daemon thread which is waiting for a lock, and you do not arrange for the lock to be released, then the main thread will hang on exit.

As Patrick mentioned, you can exit your program more directly by using exit_, but this bypasses all cleanup functions and may not be appropriate for your application.

like image 198
Stephan A. Terre Avatar answered Sep 22 '22 02:09

Stephan A. Terre