[libc-commits] [libc] [libc] implement pthread_mutex_trylock (PR #93359)

via libc-commits libc-commits at lists.llvm.org
Fri May 24 17:33:17 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libc

Author: Nhat Nguyen  (changkhothuychung)

<details>
<summary>Changes</summary>

fix issue #<!-- -->85278

---
Full diff: https://github.com/llvm/llvm-project/pull/93359.diff


1 Files Affected:

- (modified) libc/src/__support/threads/linux/mutex.h (+21-1) 


``````````diff
diff --git a/libc/src/__support/threads/linux/mutex.h b/libc/src/__support/threads/linux/mutex.h
index 6702de4651686..c7f9b4f320dc3 100644
--- a/libc/src/__support/threads/linux/mutex.h
+++ b/libc/src/__support/threads/linux/mutex.h
@@ -116,7 +116,27 @@ struct Mutex {
     }
   }
 
-  MutexError trylock();
+  MutexError trylock() {
+    FutexWordType mutex_status = FutexWordType(LockState::Free);
+    FutexWordType locked_status = FutexWordType(LockState::Locked);
+
+    if (futex_word.compare_exchange_strong(mutex_status,
+                                           FutexWordType(LockState::Locked))) {
+      return MutexError::NONE;
+    }
+
+    switch (LockState(mutex_status)) {
+    case LockState::Locked:
+      if (recursive && this == owner) {
+        lock_count++;
+        return MutexError::NONE;
+      }
+
+    case LockState::Free:
+      // If it was LockState::Free, we shouldn't be here at all.
+      return MutexError::BAD_LOCK_STATE;
+    }
+  }
 };
 
 } // namespace LIBC_NAMESPACE

``````````

</details>


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


More information about the libc-commits mailing list