In Python, the use of reference counting to implement object management and garbage collection, that is, when other objects refer to the object, its reference count plus 1, minus 1, when the reference count is 0, is reclaimed by the garbage collector.
The Python interpreter's management of objects and counters is divided into the following two steps:
1) Its reference count minus 1
2) to determine if the reference count is 0, 0, destroy the object
Because of the use of reference counting, two problems are caused, Gil and circular references
One. GIL (Global interpreter Lock) Universal interpreter lock
Imagine using a reference count in multiple threads, such as a thread, a and a and a reference to obj, then the reference count for obj is 2.
1) When a revokes a reference to obj, just after the first step, a thread switch takes place and enters thread B
2) Just b also revokes the reference to obj, the reference count of obj becomes 0, destroys the object, frees the memory
3) switch back to thread a,a continue the second step, destroy the object .... Results unknown
To solve this problem, the Gil is introduced to guarantee the mutex (mutex) of shared resources within the virtual machine, and only one thread works at a time. If you want to use multithreading, only bypass Gil ...
Two. Circular references
Let's look at an example:
1 classLeak (object):2 def __init__(self):3 Print("object with {0} was born". Format ( self))4 5 while(True):6A =leak ()7Dleak ()8A.B =B9B.A =ATenA =None OneB = None
When creating two objects referencing each other, even if the object's two variables are finally pointed elsewhere, the reference count of the objects already created will not be 0, and will not be destroyed, causing a memory leak ...
(My computer ran for a long while no memory consumption light ...) Tragedy
This situation can be garbage collected by calling Gc.collect () that is displayed
Reference: 91 recommendations for improving Python programs 68, 69
Two interesting questions about object management and garbage collection in Python python