[Mlir-commits] [mlir] [MLIR:Python] Fix race on PyOperations. (PR #139721)

Peter Hawkins llvmlistbot at llvm.org
Wed May 14 07:57:22 PDT 2025


================
@@ -725,19 +733,27 @@ class PyOperation : public PyOperationBase, public BaseContextObject {
   /// parent context's live operations map, and sets the valid bit false.
   void erase();
 
-  /// Invalidate the operation.
-  void setInvalid() { valid = false; }
-
   /// Clones this operation.
   nanobind::object clone(const nanobind::object &ip);
 
+  /// Invalidate the operation.
+  void setInvalid() {
+    nanobind::ft_lock_guard lock(getContext()->liveOperationsMutex);
+    setInvalidLocked();
+  }
+  /// Like setInvalid(), but requires the liveOperations mutex to be held.
+  void setInvalidLocked() { valid = false; }
----------------
hawkinsp wrote:

That would be nice, wouldn't it.

Sadly `PyMutex_IsLocked` isn't a public CPython API; I filed https://github.com/python/cpython/issues/134009 for that.

It would probably be possible for nanobind to clone that code, much as we're doing for `PyUnstable_TryIncRef`, but let me wait until we hear back on the CPython issue before I send them a PR adding a `.is_locked()` method on the nanobind `ft_mutex`.

https://github.com/llvm/llvm-project/pull/139721


More information about the Mlir-commits mailing list