[vlc-devel] [PATCH 1/2] threads: add vlc_sem_trywait()

RĂ©mi Denis-Courmont remi at remlab.net
Sun Apr 12 11:14:40 CEST 2020


---
 include/vlc_threads.h | 12 ++++++++++++
 src/libvlccore.sym    |  1 +
 src/misc/threads.c    | 14 ++++++++++++++
 3 files changed, 27 insertions(+)

diff --git a/include/vlc_threads.h b/include/vlc_threads.h
index 1da9f941f7..b0aabdb624 100644
--- a/include/vlc_threads.h
+++ b/include/vlc_threads.h
@@ -508,6 +508,18 @@ VLC_API int vlc_sem_post(vlc_sem_t *);
  */
 VLC_API void vlc_sem_wait(vlc_sem_t *);
 
+/**
+ * Tries to decrement a semaphore.
+ *
+ * This function decrements the semaphore if its value is not zero.
+ *
+ * \param sem semaphore to decrement
+ *
+ * \retval 0 the semaphore was decremented
+ * \retval EAGAIN the semaphore was zero and could not be decremented
+ */
+VLC_API int vlc_sem_trywait(vlc_sem_t *sem) VLC_USED;
+
 /**
  * Waits on a semaphore within a deadline.
  *
diff --git a/src/libvlccore.sym b/src/libvlccore.sym
index b44431d3fd..a96d9100ad 100644
--- a/src/libvlccore.sym
+++ b/src/libvlccore.sym
@@ -519,6 +519,7 @@ vlc_sem_init
 vlc_sem_post
 vlc_sem_wait
 vlc_sem_timedwait
+vlc_sem_trywait
 vlc_control_cancel
 vlc_GetCPUCount
 vlc_CPU
diff --git a/src/misc/threads.c b/src/misc/threads.c
index e26a98f7cd..5bbfa7b74b 100644
--- a/src/misc/threads.c
+++ b/src/misc/threads.c
@@ -534,6 +534,20 @@ int vlc_sem_timedwait(vlc_sem_t *sem, vlc_tick_t deadline)
     return 0;
 }
 
+int vlc_sem_trywait(vlc_sem_t *sem)
+{
+    unsigned exp = atomic_load_explicit(&sem->value, memory_order_relaxed);
+
+    do
+        if (exp == 0)
+            return EAGAIN;
+    while (!atomic_compare_exchange_weak_explicit(&sem->value, &exp, exp - 1,
+                                                  memory_order_acquire,
+                                                  memory_order_relaxed));
+
+    return 0;
+}
+
 enum { VLC_ONCE_UNDONE, VLC_ONCE_DOING, VLC_ONCE_CONTEND, VLC_ONCE_DONE };
 
 static_assert (VLC_ONCE_DONE == 3, "Check vlc_once in header file");
-- 
2.26.0



More information about the vlc-devel mailing list