[vlc-devel] [PATCH 5/7] thread: add vlc_sem_timedwait()

RĂ©mi Denis-Courmont remi at remlab.net
Sun Feb 16 18:50:44 CET 2020


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

diff --git a/include/vlc_threads.h b/include/vlc_threads.h
index ab3a7e3cb5..96713b51b7 100644
--- a/include/vlc_threads.h
+++ b/include/vlc_threads.h
@@ -589,6 +589,20 @@ VLC_API int vlc_sem_post(vlc_sem_t *);
  */
 VLC_API void vlc_sem_wait(vlc_sem_t *);
 
+/**
+ * Waits on a semaphore within a dealine.
+ *
+ * This function waits for the semaphore just like vlc_sem_wait(), but only
+ * up to a given deadline.
+ *
+ * \param sem semaphore to wait for
+ * \param deadline deadline to wait until
+ *
+ * \retval 0 the semaphore was decremented
+ * \retval ETIMEDOUT the deadline was reached
+ */
+VLC_API int vlc_sem_timedwait(vlc_sem_t *sem, vlc_tick_t deadline) VLC_USED;
+
 /**
  * Initializes a read/write lock.
  */
diff --git a/src/libvlccore.sym b/src/libvlccore.sym
index fde14997b9..1d9e521662 100644
--- a/src/libvlccore.sym
+++ b/src/libvlccore.sym
@@ -521,6 +521,7 @@ vlc_ext_dialog_update
 vlc_sem_init
 vlc_sem_post
 vlc_sem_wait
+vlc_sem_timedwait
 vlc_control_cancel
 vlc_GetCPUCount
 vlc_CPU
diff --git a/src/misc/threads.c b/src/misc/threads.c
index df1a390c8e..49be4441b9 100644
--- a/src/misc/threads.c
+++ b/src/misc/threads.c
@@ -433,3 +433,23 @@ void vlc_sem_wait (vlc_sem_t *sem)
         }
     }
 }
+
+int vlc_sem_timedwait(vlc_sem_t *sem, vlc_tick_t deadline)
+{
+    unsigned exp = 1;
+
+    while (!atomic_compare_exchange_weak_explicit(&sem->value, &exp, exp - 1,
+                                                  memory_order_acquire,
+                                                  memory_order_relaxed))
+    {
+        if (likely(exp == 0))
+        {
+            if (!vlc_atomic_timedwait(&sem->value, 0, deadline))
+                return ETIMEDOUT;
+
+            exp = 1;
+        }
+    }
+
+    return 0;
+}
-- 
2.25.0



More information about the vlc-devel mailing list