[libc-commits] [libc] [libc][semaphore] Add post and wait operations for internal semaphore (PR #198959)
Michael Jones via libc-commits
libc-commits at lists.llvm.org
Thu Jul 16 14:50:05 PDT 2026
================
@@ -8,24 +8,129 @@
#include "hdr/errno_macros.h"
#include "hdr/fcntl_macros.h"
+#include "hdr/time_macros.h"
+#include "hdr/types/struct_timespec.h"
+#include "src/__support/time/clock_gettime.h"
#include "src/semaphore/linux/semaphore.h"
#include "test/UnitTest/Test.h"
using LIBC_NAMESPACE::Semaphore;
TEST(LlvmLibcSemaphoreTest, InitAndGetValue) {
- Semaphore sem(3);
+ Semaphore sem(3, /*is_shared=*/false);
ASSERT_TRUE(sem.is_valid());
ASSERT_EQ(sem.getvalue(), 3);
}
TEST(LlvmLibcSemaphoreTest, Destroy) {
- Semaphore sem(5);
+ Semaphore sem(5, /*is_shared=*/false);
ASSERT_TRUE(sem.is_valid());
sem.destroy();
ASSERT_FALSE(sem.is_valid());
}
+TEST(LlvmLibcSemaphoreTest, TryWait) {
+ Semaphore sem(2, /*is_shared=*/false);
+
+ // two successful non-blocking decrements.
+ ASSERT_EQ(sem.trywait(), 0);
+ ASSERT_EQ(sem.trywait(), 0);
+ ASSERT_EQ(sem.getvalue(), 0);
+
+ // value is now zero, trywait must fail with EAGAIN.
+ ASSERT_EQ(sem.trywait(), EAGAIN);
+ ASSERT_EQ(sem.getvalue(), 0);
+}
+
+TEST(LlvmLibcSemaphoreTest, Post) {
+ Semaphore sem(0, /*is_shared=*/false);
+ ASSERT_EQ(sem.getvalue(), 0);
+
+ ASSERT_EQ(sem.post(), 0);
+ ASSERT_EQ(sem.getvalue(), 1);
+
+ // the posted value can be consumed by trywait.
+ ASSERT_EQ(sem.trywait(), 0);
+ ASSERT_EQ(sem.getvalue(), 0);
+}
+
+TEST(LlvmLibcSemaphoreTest, WaitNonBlocking) {
+ Semaphore sem(2, /*is_shared=*/false);
+
+ // value is positive: wait() should decrement without blocking.
+ ASSERT_EQ(sem.wait(), 0);
+ ASSERT_EQ(sem.getvalue(), 1);
+ ASSERT_EQ(sem.wait(), 0);
+ ASSERT_EQ(sem.getvalue(), 0);
+}
+
+TEST(LlvmLibcSemaphoreTest, TimedWaitNonBlocking) {
----------------
michaelrj-google wrote:
The standard says: "Under no circumstance shall the function fail with a timeout if the semaphore can be locked immediately. The validity of the abstime need not be checked if the semaphore can be locked immediately."
Add a test to cover this case. Specifically I want you to pass a null `abstime` to ensure it's never dereferenced.
https://github.com/llvm/llvm-project/pull/198959
More information about the libc-commits
mailing list