2011.02.21 01:10
파이썬 가비지 콜렉터 관련 정리해둔거 (작성자: azki)



Since Python makes heavy use of malloc() and free(), it needs a strategy to avoid memory leaks as well as the use of freed memory. The chosen method is called reference counting. The principle is simple: every object contains a counter, which is incremented when a reference to the object is stored somewhere, and which is decremented when a reference to it is deleted. When the counter reaches zero, the last reference to the object has been deleted and the object is freed.


>>> import gc
>>> gc.set_debug(gc.DEBUG_LEAK)
>>> class ss:
...     def __del__(self):
...             print 'del:' + self.str
...
>>> gc.collect()
0
>>> gc.garbage
[]
>>> a = ss()
>>> b = ss()
>>> c = ss()
>>> a.str = 'aa'
>>> b.str = 'bb'
>>> c.str = 'cc'
>>> gc.collect()
0
>>> gc.garbage
[]
>>> del c
del:cc
>>> gc.garbage
[]
>>> gc.collect()
0
>>> a.k = b
>>> b.k = a
>>> del a
>>> del b
>>> gc.garbage
[]
>>> gc.collect()
gc: uncollectable <ss instance at 02560238>
gc: uncollectable <ss instance at 025601C0>
gc: uncollectable <dict 02561780>
gc: uncollectable <dict 025618A0>
4
>>> gc.garbage
[<__main__.ss instance at 0x02560238>, <__main__.ss instance at 0x025601C0>, {'k
': <__main__.ss instance at 0x025601C0>, 'str': 'bb'}, {'k': <__main__.ss instan
ce at 0x02560238>, 'str': 'aa'}]
>>> for a in gc.garbage[-2:]: a['k'] = None
...
>>> gc.garbage
[<__main__.ss instance at 0x02560238>, <__main__.ss instance at 0x025601C0>, {'k
': None, 'str': 'bb'}, {'k': None, 'str': 'aa'}]
>>> del gc.garbage[:]
del:aa
del:bb
>>> gc.garbage
[]
>>> gc.collect()
0
신고
Posted by 아즈키

댓글을 달아 주세요