[pypy-commit] pypy lightweight-finalizers: A branch to try to implement lightweight finalizers for the common case of

fijal noreply at buildbot.pypy.org
Thu Sep 29 20:39:53 CEST 2011


Author: Maciej Fijalkowski <fijall at gmail.com>
Branch: lightweight-finalizers
Changeset: r47691:2a406eb4b53d
Date: 2011-09-29 15:37 -0300
http://bitbucket.org/pypy/pypy/changeset/2a406eb4b53d/

Log:	A branch to try to implement lightweight finalizers for the common
	case of an object owning some raw memory. Interface so far

diff --git a/pypy/rlib/rgc.py b/pypy/rlib/rgc.py
--- a/pypy/rlib/rgc.py
+++ b/pypy/rlib/rgc.py
@@ -440,3 +440,20 @@
     def specialize_call(self, hop):
         hop.exception_is_here()
         return hop.genop('gc_typeids_z', [], resulttype = hop.r_result)
+
+# ----------------------------------------------------------------------
+
+def owns_raw_memory(name):
+    """ Declare class as owning raw memory under the attribute name. When
+    object is freed, it'll automatically free the raw memory residing
+    under this attribute
+    """
+    def wrapper(cls):
+        def remove_raw_mem_attr(self):
+            if getattr(self, name):
+                lltype.free(getattr(self, name), flavor='raw')
+        
+        cls._raw_mem_ptr_name = name
+        cls.__del__ = remove_raw_mem_attr
+        return cls
+    return wrapper
diff --git a/pypy/rlib/test/test_rgc.py b/pypy/rlib/test/test_rgc.py
--- a/pypy/rlib/test/test_rgc.py
+++ b/pypy/rlib/test/test_rgc.py
@@ -171,3 +171,23 @@
     x1 = X()
     n = rgc.get_rpy_memory_usage(rgc.cast_instance_to_gcref(x1))
     assert n >= 8 and n <= 64
+
+def test_raw_memory_owner():
+    T = lltype.Struct('X', ('x', lltype.Signed))
+
+    @rgc.owns_raw_memory('p')
+    class X(object):
+        p = lltype.nullptr(T)
+        
+        def __init__(self, arg):
+            if arg:
+                self.p = lltype.malloc(T, flavor='raw')
+    
+    a = X(3)
+    b = X(0)
+    ptr2 = b.p
+    ptr = a.p
+    del a, b
+    gc.collect()
+    assert ptr._was_freed()
+    assert not ptr2


More information about the pypy-commit mailing list