开发者

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, k开发者_Go百科wargs)

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜