我像这里所展示的那样杀死线程:在Python中有没有办法杀死一个线程?
但是我注意到,内存没有被释放(gc.get_objects()
不断增长)。实际上,这些对象是列表、字典等,而不是文件。
有没有办法手动释放资源? 代码:
import ctypes
def terminate_thread(thread):
"""Terminates a python thread from another thread.
:param thread: a threading.Thread instance
"""
if not thread.isAlive():
return
exc = ctypes.py_object(SystemExit)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_long(thread.ident), exc)
if res == 0:
raise ValueError("nonexistent 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(thread.ident, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None
self.error = None
def run(self):
try:
self.result = myfun(*args, **kw) #run external resource and the interrupt it
except Exception as e:
self.error = e
c = MyThread()
c.start()
c.join(60) # wait a minute
counter = 0
if c.isAlive():
while c.isAlive():
time.sleep(0.1)
try:
terminate_thread(c) # how to release resources?
except:
break
counter += 1
if counter > 10: break
raise TimeoutException
输出示例:
print('Controlled objects: %s' % len(gc.get_objects()))
print ('Unreachable: %s' % gc.collect())
Controlled objects: 85084 #request 1, no timeout
Unreachable: 5640
Controlled objects: 171994 # request 2, timeout
Unreachable: 7221
myfun
是外部函数,则在您复制的示例中注意注释:正如文档中所述,这并不是万能解决方案,因为如果线程在Python解释器之外忙碌,它将无法捕获中断。
- Mark Tolonen