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.
>>> 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
'서버 기타' 카테고리의 다른 글
| python gc and reference cycles. (0) | 2011/02/21 |
|---|---|
| 이클립스(eclipse)가 시동 시 응답없음. (building workspace 0%) (0) | 2010/10/05 |
| Git 사용기 (windows 환경에서 GIT-GUI 와 github.com 을 중점으로) (10) | 2010/05/19 |
| SourceSafe Error 'Cannot find SS.INI for user' (0) | 2009/02/06 |
| apache2 mod_deflate (gzip) (0) | 2008/05/14 |
| ALTER TABLE 로 테이블명 바꾸기 / 컬럼명 바꾸기 (0) | 2008/05/07 |