假设我从 threading.Thread 派生:
from threading import Thread
class Worker(Thread):
def start(self):
self.running = True
Thread.start(self)
def terminate(self):
self.running = False
self.join()
def run(self):
import time
while self.running:
print "running"
time.sleep(1)
此类的任何线程启动的实例都必须主动终止它的线程,然后才能进行垃圾回收(线程本身持有一个引用)。所以这是一个问题,因为它完全违背了垃圾回收的目的。在那种情况下,有一些对象封装了一个线程,并且随着对象的最后一个实例超出范围,析构函数被调用以进行线程终止和清理。因此是析构函数
def __del__(self):
self.terminate()
不会成功。
我认为唯一能很好地封装线程的方法是使用低级 thread
内置模块和 weakref
弱引用。或者我可能遗漏了一些基本的东西。那么有没有比在 weakref
意大利面条代码中纠缠不清更好的方法呢?
最佳答案
如何使用包装类(它有一个 Thread
而不是一个 Thread
)?
例如:
class WorkerWrapper:
__init__(self):
self.worker = Worker()
__del__(self):
self.worker.terminate()
然后在客户端代码中使用这些包装类,而不是直接在线程中使用。
或者我错过了什么(:
关于Python threading.Thread、范围和垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8359469/