[libc-commits] [libc] [libc] implement pthread_mutex_trylock (PR #93359)
Nhat Nguyen via libc-commits
libc-commits at lists.llvm.org
Fri May 24 17:32:49 PDT 2024
https://github.com/changkhothuychung created https://github.com/llvm/llvm-project/pull/93359
fix issue #85278
>From 2e257d35d0da487b738c6e8f877df36470ea63cc Mon Sep 17 00:00:00 2001
From: changkhothuychung <nhat7203 at gmail.com>
Date: Fri, 24 May 2024 20:30:13 -0400
Subject: [PATCH] init attempt
---
libc/src/__support/threads/linux/mutex.h | 22 +++++++++++++++++++++-
1 file changed, 21 insertions(+), 1 deletion(-)
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
More information about the libc-commits
mailing list