[Mlir-commits] [mlir] [mlir][python] Cache import of ir module in	type casters. (PR #160000)
    Oleksandr Alex Zinenko 
    llvmlistbot at llvm.org
       
    Mon Sep 22 02:06:50 PDT 2025
    
    
  
================
@@ -30,6 +32,57 @@
 // clang-format on
 #include "llvm/ADT/Twine.h"
 
+namespace mlir {
+namespace python {
+namespace {
+
+// Safely calls Python initialization code on first use, avoiding deadlocks.
+template <typename T>
+class SafeInit {
+public:
+  typedef std::unique_ptr<T> (*F)();
+
+  explicit SafeInit(F init_fn) : init_fn_(init_fn) {}
+
+  T &Get() {
+    if (T *result = output_.load()) {
+      return *result;
+    }
+
+    // Note: init_fn() may be called multiple times if, for example, the GIL is
+    // released during its execution. The intended use case is for module
+    // imports which are safe to perform multiple times. We are careful not to
+    // hold a lock across init_fn() to avoid lock ordering problems.
+    std::unique_ptr<T> m = init_fn_();
+    {
+      nanobind::ft_lock_guard lock(mu_);
+      if (T *result = output_.load()) {
----------------
ftynse wrote:
```suggestion
    std::unique_ptr<T> m = initFn();
    {
      nanobind::ft_lock_guard lock(mu);
      if (T *result = output.load()) {
```
https://github.com/llvm/llvm-project/pull/160000
    
    
More information about the Mlir-commits
mailing list