Python多进程与多线程调用terminate报错:NoneType对象无该属性
解决Python进程/线程无法正常终止的问题
错误根源
- 变量赋值错误:你把
Thread.start()和Process.start()的返回值(None)赋值给了thread1和thread2,后续调用terminate()时实际是对None对象操作,触发NoneType object has no attribute terminate错误。 - 线程无强制终止方法:Python的
threading.Thread没有内置的terminate()方法,不能直接强制终止,必须通过协作式逻辑让线程自行停止。
修正后的实现代码
import multiprocessing import threading import time # 全局停止标志,用于线程的协作式退出 stop_flag = False def main_thread(): print('here') k = 0 while not stop_flag: k += 1 if k == 10: terminate_it() print(f'hello world {k}') time.sleep(0.1) # 控制输出频率,避免刷屏 def terminate_it(): global stop_flag, thread1, thread2 # 触发线程的停止逻辑 stop_flag = True # 终止并回收进程资源 if thread1.is_alive(): thread1.terminate() thread1.join() # 等待线程自行退出 if thread2.is_alive(): thread2.join() # 正确创建进程/线程实例:先实例化对象,再调用start() thread2 = threading.Thread(target=main_thread) thread2.start() thread1 = multiprocessing.Process(target=main_thread) thread1.start() # 示例:主线程等待2秒后触发终止操作(可根据需求调整触发时机) time.sleep(2) terminate_it()
关键说明
- 保存实例引用:必须先创建
Thread或Process实例并赋值给变量,再调用start(),这样变量才会持有有效的进程/线程对象,而非None。 - 线程协作停止:通过全局
stop_flag变量让线程的循环条件不成立,从而自行退出,这是Python线程安全的停止方式,避免强制终止引发的资源泄漏问题。 - 进程终止处理:进程支持
terminate()强制终止,之后务必调用join()等待进程资源完全回收。
内容的提问来源于stack exchange,提问作者uma shankar
相关产品推荐
相关产品推荐

