Python在子线程无线循环的过程中,如果直接ctrl+c结束程序的话,虽然程序可以结束,但是会导致子线程资源无法回收,一般情况不会有太大影响,但是使用TCP通信的时候,子线程是占用特定的端口的,在资源没有回收的情况下,再次启动程序就会报端口占用错误。
所以参考https://blog.youkuaiyun.com/hp_cpp/article/details/83040162博主的方法如下强制结束子线程:
import inspect
import ctypes
from threading import Thread
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident,