Python线程线程,作用域和垃圾回收

问题描述:

说我是从threading.Thread派生的:

Say I derive from 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)

此类已启动线程的任何实例必须先将其线程主动终止,然后才能收集垃圾(该线程本身拥有引用)。所以这是一个问题,因为它完全违背了垃圾回收的目的。在那种情况下,有一些对象封装线程,并且对象的最后一个实例超出范围,则析构函数将被调用以终止线程并进行清理。因此就是析构函数

Any instance of this class with the thread being started must have it's thread actively terminated before it can get garbage collected (the thread holds a reference itself). So this is a problem, because it completely defies the purpose of garbage collection. In that case having some object encapsulating a thread, and with the last instance of the object going out of scope the destructor gets called for thread termination and cleanup. Thuss a destructor

    def __del__(self):
        self.terminate()

不会解决问题。

我看到的很好封装的唯一方法线程是通过使用低级 thread 内置模块和 weakref 弱引用来实现的。否则我可能缺少一些基本知识。因此,有没有比在 weakref 意大利面条代码中纠缠起来更好的方法了?

The only way I see to nicely encapsulate threads is by using low level thread builtin module and weakref weak references. Or I may be missing something fundamental. So is there a nicer way than tangling things up in weakref spaghetti code?

如何使用包装类(具有- Thread 而不是-a Thread )?

How about using a wrapper class (which has-a Thread rather than is-a Thread)?

例如:

class WorkerWrapper:
    __init__(self):
        self.worker = Worker()
    __del__(self):
        self.worker.terminate()

然后在客户端代码中使用这些包装器类,而不是直接使用线程。

And then use these wrapper classes in client code, rather than threads directly.

或者我可能想念一些(:

Or perhaps I miss something (: