【发布时间】:2013-12-18 22:47:03
【问题描述】:
我正在开发一个 python 程序来监视和控制游戏服务器。游戏服务器有许多游戏核心,这些核心处理客户端。
我有一个名为Server 的python 类,它包含Core 类的实例,这些实例用于管理实际的游戏核心。 Core 类需要通过 TCP-Socket 连接到游戏核心,以便向特定游戏核心发送命令。要正确关闭这些套接字,Core 类有一个 __del__ 方法来关闭套接字。
一个例子:
class Server(object):
Cores = [] # list which will be filled with the Core objects
def __init__(self):
# detect the game-cores, create the core objects and append them to self.Cores
class Core(object):
CoreSocket = None # when the socket gets created, the socket-object will be bound to this variable
def __init__(self, coreID):
# initiate the socket connection between the running game-core and this python object
def __del__(self):
# properly close the socket connection
现在,当我使用 Core 类本身时,析构函数总是被正确调用。但是当我使用 Server 类时,Server.Cores 中的 Core 对象 永远不会被破坏。 我读过 gc 在循环引用和带有析构函数的类方面存在问题,但是 @ 987654331@ 对象从不引用Server 对象(只有套接字对象,在Core.CoreSocket 中),因此不会创建循环引用。
我通常更喜欢使用with-statement 进行资源清理,但在这种情况下,我需要通过Server 类中的许多不同方法发送命令,因此使用with 将无济于事......我还尝试在每个命令上创建和关闭套接字,但是当我需要发送许多命令时,这确实会降低性能。使用weakref 模块创建的弱引用也无济于事,因为在我创建Server 对象后立即调用析构函数。
当Server 对象被gc 清理时,为什么Core 对象没有被正确破坏?我想我只是忘记了一些简单的事情,但我就是不知道它是什么。
或者也许有更好的方法可以在清理对象时关闭这些套接字?
【问题讨论】:
标签: python python-2.7 destructor resource-cleanup