[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:49 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()) {
+ return *result;
+ }
+ T *p = m.release();
+ output_.store(p);
+ return *p;
+ }
+ }
+
+private:
+ nanobind::ft_mutex mu_;
+ std::atomic<T *> output_{nullptr};
+ F init_fn_;
----------------
ftynse wrote:
```suggestion
nanobind::ft_mutex mu;
std::atomic<T *> output{nullptr};
F initFn;
```
Nit: LLVM naming convention
https://github.com/llvm/llvm-project/pull/160000
More information about the Mlir-commits
mailing list