When I use the old Python thread
API everything works fine:
thread.start_new_thread(main_func, args, kwargs)
But if I try to use the new threading API the process, which runs the thread hangs when it should exit itself with sys.exit(3)
:
threading.Thread(target=main_func, args=args, kwargs=kwargs).start()
How can I translate the code to the new threading API?
You can see this example in context.
This behavior is due to the fact that thread.start_new_thread
creates a thread in daemon
mode while threading.Thread
creates a thread in non-daemon
mode.
To start threading.Thread
in daemon mode, you need to use .setDaemon
method:
my_thread = threading.Thread(target=main_func, args=args, kwargs=kwargs)
my_thread.setDaemon(True)
my_thread.start()
The program will exit when all non-daemon threads have exited. You can make your secondary Thread
daemonic by setting its daemon
property to True
.
Alternatively you can replace your call to sys.exit
with os._exit
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With