Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate `thread.start_new_thread(...)` to the new threading API

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.

like image 867
deamon Avatar asked Oct 23 '10 11:10

deamon


2 Answers

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()
like image 50
suzanshakya Avatar answered Oct 06 '22 00:10

suzanshakya


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.

like image 43
adw Avatar answered Oct 06 '22 01:10

adw