Wil*_*ert 5 python python-multithreading
我想在主程序停止时停止Python线程。它用于连接到服务器的类。连接由后台线程维护,前台线程响应回调。以下是一个最小的示例。
#!/usr/bin/python
import time, threading
class test():
running = False
def __init__(self):
print "init"
self.running = True
self.thread = threading.Thread(target = self.startThread)
self.thread.start()
def __del__(self):
running = False
print "del"
def startThread(self):
print "thread start"
while self.running:
time.sleep(1)
print "thread running"
a = test()
Run Code Online (Sandbox Code Playgroud)
当程序结束时,我天真地期望调用 __del__() 以便通知后台线程停止,但直到后台线程停止后才调用 i。显式调用某些函数不是一个选项,因为该类已被其他人使用,我不想强迫他们使用一些额外的代码行。
__del__只要存在对 的引用self,并且后台线程本身中有一个这样的引用:在 的self参数中,就不会被调用def startThread(self):。
您需要将运行后台线程的函数移到类之外。__del__我建议使用弱引用,而不是使用弱引用,如下所示。此代码应该在没有该__del__()方法且不使用self.running属性的情况下工作。
self.thread = threading.Thread(target=run_me, args=(weakref.ref(self),))
...
def run_me(weak_self):
"Global function"
while True:
self = weak_self()
if self is None: break # no more reference to self
...
del self # forget this reference for now
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)