简体   繁体   中英

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM