将`thread.start_new_thread(...)`转换为新的线程API

5 投票
2 回答
6009 浏览
提问于 2025-04-16 05:57

当我使用旧的 Python thread 接口时,一切都运行得很好:

thread.start_new_thread(main_func, args, kwargs)

但是如果我尝试使用新的 threading 接口,运行线程的进程在应该用 sys.exit(3) 退出时却卡住了:

threading.Thread(target=main_func, args=args, kwargs=kwargs).start()

我该如何将代码转换为新的 threading 接口呢?

你可以在 这个链接 中查看这个例子。

2 个回答

2

当所有非守护线程都结束时,程序会退出。你可以通过把你的第二个 Threaddaemon 属性设置为 True 来让它变成守护线程。

另外,你也可以把调用 sys.exit 的地方换成 os._exit

8

这个行为是因为 thread.start_new_thread 创建的线程是“守护线程”模式,而 threading.Thread 创建的线程是“非守护线程”模式。
如果你想让 threading.Thread 以守护线程的模式启动,你需要使用 .setDaemon 方法:

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

撰写回答