views:

19

answers:

2

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.

+1  A: 

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.

adw
+2  A: 

This behavior is due to the fact that thread.start_new_thread creates thread in daemon mode while threading.Thread creates thread in non-daemon mode.
So you need to start thread in daemon mode:

my_thread = threading.Thread(target=main_func, args=args, kwargs=kwargs)
my_thread.setDaemon(True)
my_thread.start()
suzanshakya