我如何垃圾收集'当我需要通知其他对象时,一个人死了?

时间:2017-04-20 02:42:02

标签: python reference garbage-collection

我正在a language that compiles to Brainfuck上工作,当他们的一个人被垃圾收集时,我需要帮助才能更新这些对象' (擦拭其内存并分流许多插槽留下的其他内存),以便它们引用内存中的正确位置。但是,保持一个对象列表来更新它们的问题是Python的垃圾收集器现在不能为我做艰苦的工作,因为它们在我们的对象列表中仍然有一个有效的引用,即使它是正在使用的内容将被删除。

TLDR:参见示例代码。

class Array_Claim:
    def __init__(self,array,index,del_enabled = False):
        self.index = index
        self.array = array
        self.del_enabled = del_enabled
    def value(self):
        return self.array.get(self.index)
    def delete(self):
        self.array.delete(self.index)
    def __del__(self):
        if(self.del_enabled):
            print("Del method called!")
            self.delete()

class Array:
    def __init__(self):
        self._array = []
        self._claims = [] #we need to update the other claim's indexes after one is deleted
    def new(self,value,del_enabled = False):
        self._array.append(value)
        result = Array_Claim(self,len(self._array)-1,del_enabled)
        self._claims.append(result)
        return result
    def delete(self,index):
        self._array.pop(index)
        self._claims.pop(index)
        for i in range(index,len(self._claims)):
            self._claims[i].index = i 
    def add(self,claim1,claim2):
        return self.new(self._array[claim1.index] + self._array[claim2.index])

#works fine when del isn't enabled.
print("Test one")
array = Array()
var = array.new(5)
var.delete()
print(array._array)

#However,we have problems collecting anonymous objects now
print("Test 2")
array = Array()
var = array.add(array.new(2),array.new(3))
var.delete()
print(array._array)

#Let's try enabling our del method!
print("Test 3")
#works
array = Array()
var = array.new(5,True)
var.delete()
print(array._array)

#crashes and burns because it was deleted twice somehow...
print("Test 4")
array = Array()
var = array.new(5,True)
del var
print(array._array)

#Our anonymous objects that we did this for don't even collect theirselves!
print("Test 5")
array = Array()
array.add(array.new(2),array.new(3))
print(array._array)

0 个答案:

没有答案