From 89a5074dd68af1e9457954f481eee2294ff83e04 Mon Sep 17 00:00:00 2001
From: Andreas Kloeckner <inform@tiker.net>
Date: Tue, 6 Jun 2017 11:13:34 -0400
Subject: [PATCH] Ensure that CL objects can continue to be cleaned up even
 when PyOpenCL is already half-deleted

---
 pyopencl/cffi_cl.py | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)

diff --git a/pyopencl/cffi_cl.py b/pyopencl/cffi_cl.py
index 2d76f916..b85400cb 100644
--- a/pyopencl/cffi_cl.py
+++ b/pyopencl/cffi_cl.py
@@ -223,8 +223,22 @@ class _Common(object):
         return self
     ptr = _ffi.NULL
 
+    # {{{ cleanup
+
+    # The module-global _lib variable may get set to None during interpreter
+    # cleanup before we're done cleaning up CL objects. (Symbols starting with
+    # an underscore even get cleared first [1]--although it's unclear that that
+    # really matters.) To retain our ability to clean up objects, retain a
+    # reference to the _lib module.
+    #
+    # [1] https://www.python.org/doc/essays/cleanup/
+
+    _retained_lib = _lib
+
     def __del__(self):
-        _lib.clobj__delete(self.ptr)
+        self._retained_lib.clobj__delete(self.ptr)
+
+    # }}}
 
     def __eq__(self, other):
         return other.int_ptr == self.int_ptr
-- 
GitLab