How to control object destruction order with Micropython GC? #14287
Replies: 3 comments 6 replies
-
I'm puzzled over why you should care about an unreferenced object. How would you even know it was unhappy? In any event, my understanding of the GC is that while A is referenced by B, it won't be collected. B will be collected first. This causes A to be unreferenced and it will be collected. |
Beta Was this translation helpful? Give feedback.
-
What type of resource is at issue here? If it's a memory region such as an If it's an object like a with A() as a_instance:
# Use the instance. A.__exit__() takes down the resource If the resource is owned by the A class rather than by the A instance, the approach is similar with A maintaining a class variable instance counter (taking the shared resource down when the counter reaches zero). |
Beta Was this translation helpful? Give feedback.
-
@trentp-igor The filesystem won't become unreferenced. Consider this: def setup():
flash = get_device() # Return a reference to a Flash object
os.mount(flash, "/fl_ext") On exit from the function, the local variable Re objects owned by the class: class Foo:
@classmethod
def initiate(cls):
cls.resource = get_device() # Return a reference to some object Instances can access the resource via If you want to deallocate the device you will need to take control. As I suggested above, one way is to create instances in a context manager, As a general point it is quite difficult to make MicroPython leak memory. I can think of three techniques, only one of which is remotely common. None relate to object destruction order. I am wary of the use of |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I created an new micropython object, which wraps a resource provided by a library. This resource must be allocated and freed. I use
m_new_obj_with_finaliser()
to cause the delete method to be called when the object is GCed, to free this resource.Suppose I create a new object of this type, called A, and then another object is created, B, and object B uses object A. The only reference to A is contained by object B.
Now B becomes unreferenced.
My understanding is the GC will now discover that neither A nor B can be found by following any referenced objects. And both can be garbage collected, in any order. The problem is that B still uses A. Garbage collecting A first causes a problem when B still exists and is still using it.
Beta Was this translation helpful? Give feedback.
All reactions