thread: rationalise vlc_atomic_timedwait()
[vlc.git] / include / vlc_threads.h
blob31ca8de5562b7612f6acd86504a8f6cc423be1c4
1 /*****************************************************************************
2 * vlc_threads.h : threads implementation for the VideoLAN client
3 * This header provides portable declarations for mutexes & conditions
4 *****************************************************************************
5 * Copyright (C) 1999, 2002 VLC authors and VideoLAN
6 * Copyright © 2007-2016 Rémi Denis-Courmont
8 * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
9 * Samuel Hocevar <sam@via.ecp.fr>
10 * Gildas Bazin <gbazin@netcourrier.com>
11 * Christophe Massiot <massiot@via.ecp.fr>
13 * This program is free software; you can redistribute it and/or modify it
14 * under the terms of the GNU Lesser General Public License as published by
15 * the Free Software Foundation; either version 2.1 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License for more details.
23 * You should have received a copy of the GNU Lesser General Public License
24 * along with this program; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26 *****************************************************************************/
28 #ifndef VLC_THREADS_H_
29 #define VLC_THREADS_H_
31 #ifndef __cplusplus
32 #include <stdatomic.h>
33 #endif
35 /**
36 * \ingroup os
37 * \defgroup thread Threads and synchronization primitives
38 * @{
39 * \file
40 * Thread primitive declarations
43 /**
44 * Issues an explicit deferred cancellation point.
46 * This has no effects if thread cancellation is disabled.
47 * This can be called when there is a rather slow non-sleeping operation.
48 * This is also used to force a cancellation point in a function that would
49 * otherwise <em>not always</em> be one (block_FifoGet() is an example).
51 VLC_API void vlc_testcancel(void);
53 #if defined (_WIN32)
54 # include <process.h>
55 # ifndef ETIMEDOUT
56 # define ETIMEDOUT 10060 /* This is the value in winsock.h. */
57 # endif
59 typedef struct vlc_thread *vlc_thread_t;
60 # define VLC_THREAD_CANCELED NULL
62 typedef unsigned long vlc_osthread_t;
63 #define vlc_thread_equal(a,b) ((a) == (b))
65 # define LIBVLC_NEED_SLEEP
66 typedef struct
68 bool dynamic;
69 union
71 struct
73 bool locked;
74 unsigned long contention;
76 CRITICAL_SECTION mutex;
78 } vlc_mutex_t;
79 #define VLC_STATIC_MUTEX { false, { { false, 0 } } }
80 #define LIBVLC_NEED_CONDVAR
81 #define LIBVLC_NEED_RWLOCK
82 typedef INIT_ONCE vlc_once_t;
83 #define VLC_STATIC_ONCE INIT_ONCE_STATIC_INIT
84 typedef struct vlc_threadvar *vlc_threadvar_t;
85 typedef struct vlc_timer *vlc_timer_t;
87 # define VLC_THREAD_PRIORITY_LOW 0
88 # define VLC_THREAD_PRIORITY_INPUT THREAD_PRIORITY_ABOVE_NORMAL
89 # define VLC_THREAD_PRIORITY_AUDIO THREAD_PRIORITY_HIGHEST
90 # define VLC_THREAD_PRIORITY_VIDEO 0
91 # define VLC_THREAD_PRIORITY_OUTPUT THREAD_PRIORITY_ABOVE_NORMAL
92 # define VLC_THREAD_PRIORITY_HIGHEST THREAD_PRIORITY_TIME_CRITICAL
94 static inline int vlc_poll(struct pollfd *fds, unsigned nfds, int timeout)
96 int val;
98 vlc_testcancel();
99 val = poll(fds, nfds, timeout);
100 if (val < 0)
101 vlc_testcancel();
102 return val;
104 # define poll(u,n,t) vlc_poll(u, n, t)
106 #elif defined (__OS2__)
107 # include <errno.h>
109 typedef struct vlc_thread *vlc_thread_t;
110 #define VLC_THREAD_CANCELED NULL
112 typedef unsigned long vlc_osthread_t;
113 #define vlc_thread_equal(a,b) ((a) == (b))
115 typedef struct
117 bool dynamic;
118 union
120 struct
122 bool locked;
123 unsigned long contention;
125 HMTX hmtx;
127 } vlc_mutex_t;
128 #define VLC_STATIC_MUTEX { false, { { false, 0 } } }
129 typedef struct
131 HEV hev;
132 unsigned waiters;
133 HEV hevAck;
134 unsigned signaled;
135 } vlc_cond_t;
136 #define VLC_STATIC_COND { NULLHANDLE, 0, NULLHANDLE, 0 }
137 #define LIBVLC_NEED_RWLOCK
138 typedef struct
140 unsigned done;
141 vlc_mutex_t mutex;
142 } vlc_once_t;
143 #define VLC_STATIC_ONCE { 0, VLC_STATIC_MUTEX }
144 typedef struct vlc_threadvar *vlc_threadvar_t;
145 typedef struct vlc_timer *vlc_timer_t;
147 # define VLC_THREAD_PRIORITY_LOW 0
148 # define VLC_THREAD_PRIORITY_INPUT \
149 MAKESHORT(PRTYD_MAXIMUM / 2, PRTYC_REGULAR)
150 # define VLC_THREAD_PRIORITY_AUDIO MAKESHORT(PRTYD_MAXIMUM, PRTYC_REGULAR)
151 # define VLC_THREAD_PRIORITY_VIDEO 0
152 # define VLC_THREAD_PRIORITY_OUTPUT \
153 MAKESHORT(PRTYD_MAXIMUM / 2, PRTYC_REGULAR)
154 # define VLC_THREAD_PRIORITY_HIGHEST MAKESHORT(0, PRTYC_TIMECRITICAL)
156 # define pthread_sigmask sigprocmask
158 static inline int vlc_poll (struct pollfd *fds, unsigned nfds, int timeout)
160 static int (*vlc_poll_os2)(struct pollfd *, unsigned, int) = NULL;
162 if (!vlc_poll_os2)
164 HMODULE hmod;
165 CHAR szFailed[CCHMAXPATH];
167 if (DosLoadModule(szFailed, sizeof(szFailed), "vlccore", &hmod))
168 return -1;
170 if (DosQueryProcAddr(hmod, 0, "_vlc_poll_os2", (PFN *)&vlc_poll_os2))
171 return -1;
174 return (*vlc_poll_os2)(fds, nfds, timeout);
176 # define poll(u,n,t) vlc_poll(u, n, t)
178 #elif defined (__ANDROID__) /* pthreads subset without pthread_cancel() */
179 # include <unistd.h>
180 # include <pthread.h>
181 # include <poll.h>
182 # define LIBVLC_USE_PTHREAD_CLEANUP 1
183 # define LIBVLC_NEED_SLEEP
184 # define LIBVLC_NEED_CONDVAR
185 # define LIBVLC_NEED_RWLOCK
187 typedef struct vlc_thread *vlc_thread_t;
188 #define VLC_THREAD_CANCELED NULL
189 typedef pthread_t vlc_osthread_t;
190 #define vlc_thread_equal(a,b) pthread_equal(a,b)
191 typedef pthread_mutex_t vlc_mutex_t;
192 #define VLC_STATIC_MUTEX PTHREAD_MUTEX_INITIALIZER
193 typedef pthread_once_t vlc_once_t;
194 #define VLC_STATIC_ONCE PTHREAD_ONCE_INIT
195 typedef pthread_key_t vlc_threadvar_t;
196 typedef struct vlc_timer *vlc_timer_t;
198 # define VLC_THREAD_PRIORITY_LOW 0
199 # define VLC_THREAD_PRIORITY_INPUT 0
200 # define VLC_THREAD_PRIORITY_AUDIO 0
201 # define VLC_THREAD_PRIORITY_VIDEO 0
202 # define VLC_THREAD_PRIORITY_OUTPUT 0
203 # define VLC_THREAD_PRIORITY_HIGHEST 0
205 static inline int vlc_poll (struct pollfd *fds, unsigned nfds, int timeout)
207 int val;
211 int ugly_timeout = ((unsigned)timeout >= 50) ? 50 : timeout;
212 if (timeout >= 0)
213 timeout -= ugly_timeout;
215 vlc_testcancel ();
216 val = poll (fds, nfds, ugly_timeout);
218 while (val == 0 && timeout != 0);
220 return val;
223 # define poll(u,n,t) vlc_poll(u, n, t)
225 #elif defined (__APPLE__)
226 # define _APPLE_C_SOURCE 1 /* Proper pthread semantics on OSX */
227 # include <unistd.h>
228 # include <pthread.h>
229 /* Unnamed POSIX semaphores not supported on Mac OS X */
230 # include <mach/semaphore.h>
231 # include <mach/task.h>
232 # define LIBVLC_USE_PTHREAD_CLEANUP 1
234 typedef pthread_t vlc_thread_t;
235 #define VLC_THREAD_CANCELED PTHREAD_CANCELED
236 typedef pthread_t vlc_osthread_t;
237 #define vlc_thread_equal(a,b) pthread_equal(a,b)
238 typedef pthread_mutex_t vlc_mutex_t;
239 #define VLC_STATIC_MUTEX PTHREAD_MUTEX_INITIALIZER
240 typedef pthread_cond_t vlc_cond_t;
241 #define VLC_STATIC_COND PTHREAD_COND_INITIALIZER
242 typedef pthread_rwlock_t vlc_rwlock_t;
243 #define VLC_STATIC_RWLOCK PTHREAD_RWLOCK_INITIALIZER
244 typedef pthread_once_t vlc_once_t;
245 #define VLC_STATIC_ONCE PTHREAD_ONCE_INIT
246 typedef pthread_key_t vlc_threadvar_t;
247 typedef struct vlc_timer *vlc_timer_t;
249 # define VLC_THREAD_PRIORITY_LOW 0
250 # define VLC_THREAD_PRIORITY_INPUT 22
251 # define VLC_THREAD_PRIORITY_AUDIO 22
252 # define VLC_THREAD_PRIORITY_VIDEO 0
253 # define VLC_THREAD_PRIORITY_OUTPUT 22
254 # define VLC_THREAD_PRIORITY_HIGHEST 22
256 #else /* POSIX threads */
257 # include <unistd.h> /* _POSIX_SPIN_LOCKS */
258 # include <pthread.h>
261 * Whether LibVLC threads are based on POSIX threads.
263 # define LIBVLC_USE_PTHREAD 1
266 * Whether LibVLC thread cancellation is based on POSIX threads.
268 # define LIBVLC_USE_PTHREAD_CLEANUP 1
271 * Thread handle.
273 typedef struct
275 pthread_t handle;
276 } vlc_thread_t;
279 * Return value of a canceled thread.
281 #define VLC_THREAD_CANCELED PTHREAD_CANCELED
283 typedef pthread_t vlc_osthread_t;
284 #define vlc_thread_equal(a,b) pthread_equal(a,b)
287 * Mutex.
289 * Storage space for a mutual exclusion lock.
291 * \ingroup mutex
293 typedef pthread_mutex_t vlc_mutex_t;
296 * Static initializer for (static) mutex.
298 * \ingroup mutex
300 #define VLC_STATIC_MUTEX PTHREAD_MUTEX_INITIALIZER
303 * Condition variable.
305 * Storage space for a thread condition variable.
307 * \ingroup condvar
309 typedef pthread_cond_t vlc_cond_t;
312 * Static initializer for (static) condition variable.
314 * \note
315 * The condition variable will use the default clock, which is OS-dependent.
316 * Therefore, where timed waits are necessary the condition variable should
317 * always be initialized dynamically explicit instead of using this
318 * initializer.
320 * \ingroup condvar
322 #define VLC_STATIC_COND PTHREAD_COND_INITIALIZER
325 * Read/write lock.
327 * Storage space for a slim reader/writer lock.
329 * \ingroup rwlock
331 typedef pthread_rwlock_t vlc_rwlock_t;
334 * Static initializer for (static) read/write lock.
336 * \ingroup rwlock
338 #define VLC_STATIC_RWLOCK PTHREAD_RWLOCK_INITIALIZER
341 * One-time initialization.
343 * A one-time initialization object must always be initialized assigned to
344 * \ref VLC_STATIC_ONCE before use.
346 typedef pthread_once_t vlc_once_t;
349 * Static initializer for one-time initialization.
351 #define VLC_STATIC_ONCE PTHREAD_ONCE_INIT
354 * Thread-local key handle.
356 * \ingroup threadvar
358 typedef pthread_key_t vlc_threadvar_t;
361 * Threaded timer handle.
363 * \ingroup timer
365 typedef struct vlc_timer *vlc_timer_t;
367 # define VLC_THREAD_PRIORITY_LOW 0
368 # define VLC_THREAD_PRIORITY_INPUT 10
369 # define VLC_THREAD_PRIORITY_AUDIO 5
370 # define VLC_THREAD_PRIORITY_VIDEO 0
371 # define VLC_THREAD_PRIORITY_OUTPUT 15
372 # define VLC_THREAD_PRIORITY_HIGHEST 20
374 #endif
377 * \defgroup mutex Mutual exclusion locks
378 * @{
381 * Initializes a fast mutex.
383 * Recursive locking of a fast mutex is undefined behaviour. (In debug builds,
384 * recursive locking will cause an assertion failure.)
386 VLC_API void vlc_mutex_init(vlc_mutex_t *);
389 * Initializes a recursive mutex.
390 * \warning This is strongly discouraged. Please use normal mutexes.
392 VLC_API void vlc_mutex_init_recursive(vlc_mutex_t *);
395 * Deinitializes a mutex.
397 * The mutex must not be locked, otherwise behaviour is undefined.
399 VLC_API void vlc_mutex_destroy(vlc_mutex_t *);
402 * Acquires a mutex.
404 * If needed, this waits for any other thread to release it.
406 * \warning Beware of deadlocks when locking multiple mutexes at the same time,
407 * or when using mutexes from callbacks.
409 * \note This function is not a cancellation point.
411 VLC_API void vlc_mutex_lock(vlc_mutex_t *);
414 * Tries to acquire a mutex.
416 * This function acquires the mutex if and only if it is not currently held by
417 * another thread. This function never sleeps and can be used in delay-critical
418 * code paths.
420 * \note This function is not a cancellation point.
422 * \warning If this function fails, then the mutex is held... by another
423 * thread. The calling thread must deal with the error appropriately. That
424 * typically implies postponing the operations that would have required the
425 * mutex. If the thread cannot defer those operations, then it must use
426 * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
428 * @return 0 if the mutex could be acquired, an error code otherwise.
430 VLC_API int vlc_mutex_trylock( vlc_mutex_t * ) VLC_USED;
433 * Releases a mutex.
435 * If the mutex is not held by the calling thread, the behaviour is undefined.
437 * \note This function is not a cancellation point.
439 VLC_API void vlc_mutex_unlock(vlc_mutex_t *);
442 * Checks if a mutex is locked.
444 * Do not use this function directly. Use vlc_mutex_assert() instead.
446 * @note
447 * This function has no effects.
448 * It is only meant to be use in run-time assertions.
450 * @retval false in debug builds of LibVLC,
451 * if the mutex is not locked by the calling thread;
452 * @retval true in debug builds of LibVLC,
453 * if the mutex is locked by the calling thread;
454 * @retval true in release builds of LibVLC.
456 VLC_API bool vlc_mutex_marked(const vlc_mutex_t *) VLC_USED;
459 * Asserts that a mutex is locked by the calling thread.
461 #define vlc_mutex_assert(m) assert(vlc_mutex_marked(m))
463 /** @} */
466 * \defgroup condvar Condition variables
468 * The condition variable is the most common and generic mean for threads to
469 * wait for events triggered by other threads.
471 * See also POSIX @c pthread_cond_t .
472 * @{
475 #ifdef LIBVLC_NEED_CONDVAR
476 typedef struct
478 union {
479 #ifndef __cplusplus
480 atomic_uint value;
481 #endif
482 int cpp_value;
484 } vlc_cond_t;
485 # define VLC_STATIC_COND { 0 }
486 #endif
489 * Initializes a condition variable.
491 VLC_API void vlc_cond_init(vlc_cond_t *);
494 * Initializes a condition variable (wall clock).
496 * This function initializes a condition variable for timed waiting using the
497 * UTC wall clock time. The time reference is the same as with time() and with
498 * timespec_get() and TIME_UTC.
499 * vlc_cond_timedwait_daytime() must be instead of
500 * vlc_cond_timedwait() for actual waiting.
502 void vlc_cond_init_daytime(vlc_cond_t *);
505 * Deinitializes a condition variable.
507 * No threads shall be waiting or signaling the condition, otherwise the
508 * behavior is undefined.
510 VLC_API void vlc_cond_destroy(vlc_cond_t *);
513 * Wakes up one thread waiting on a condition variable.
515 * If any thread is currently waiting on the condition variable, at least one
516 * of those threads will be woken up. Otherwise, this function has no effects.
518 * \note This function is not a cancellation point.
520 VLC_API void vlc_cond_signal(vlc_cond_t *);
523 * Wakes up all threads waiting on a condition variable.
525 * \note This function is not a cancellation point.
527 VLC_API void vlc_cond_broadcast(vlc_cond_t *);
530 * Waits on a condition variable.
532 * The calling thread will be suspended until another thread calls
533 * vlc_cond_signal() or vlc_cond_broadcast() on the same condition variable,
534 * the thread is cancelled with vlc_cancel(), or the system causes a
535 * <em>spurious</em> unsolicited wake-up.
537 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
538 * a recursive mutex. Although it is possible to use the same mutex for
539 * multiple condition, it is not valid to use different mutexes for the same
540 * condition variable at the same time from different threads.
542 * The canonical way to use a condition variable to wait for event foobar is:
543 @code
544 vlc_mutex_lock(&lock);
545 mutex_cleanup_push(&lock); // release the mutex in case of cancellation
547 while (!foobar)
548 vlc_cond_wait(&wait, &lock);
550 // -- foobar is now true, do something about it here --
552 vlc_cleanup_pop();
553 vlc_mutex_unlock(&lock);
554 @endcode
556 * \note This function is a cancellation point. In case of thread cancellation,
557 * the mutex is always locked before cancellation proceeds.
559 * \param cond condition variable to wait on
560 * \param mutex mutex which is unlocked while waiting,
561 * then locked again when waking up.
563 VLC_API void vlc_cond_wait(vlc_cond_t *cond, vlc_mutex_t *mutex);
566 * Waits on a condition variable up to a certain date.
568 * This works like vlc_cond_wait() but with an additional time-out.
569 * The time-out is expressed as an absolute timestamp using the same arbitrary
570 * time reference as the vlc_tick_now() and vlc_tick_wait() functions.
572 * \note This function is a cancellation point. In case of thread cancellation,
573 * the mutex is always locked before cancellation proceeds.
575 * \param cond condition variable to wait on
576 * \param mutex mutex which is unlocked while waiting,
577 * then locked again when waking up
578 * \param deadline <b>absolute</b> timeout
580 * \warning If the variable was initialized with vlc_cond_init_daytime(), or
581 * was statically initialized with \ref VLC_STATIC_COND, the time reference
582 * used by this function is unspecified (depending on the implementation, it
583 * might be the Unix epoch or the vlc_tick_now() clock).
585 * \return 0 if the condition was signaled, an error code in case of timeout.
587 VLC_API int vlc_cond_timedwait(vlc_cond_t *cond, vlc_mutex_t *mutex,
588 vlc_tick_t deadline);
590 int vlc_cond_timedwait_daytime(vlc_cond_t *, vlc_mutex_t *, time_t);
592 /** @} */
595 * \defgroup semaphore Semaphores
597 * The semaphore is the simplest thread synchronization primitive, consisting
598 * of a simple counter.
600 * See also POSIX @c sem_t .
602 * @{
605 * Semaphore.
607 * Storage space for a thread-safe semaphore.
609 typedef struct
611 union {
612 #ifndef __cplusplus
613 atomic_uint value;
614 #endif
615 int dummy;
617 } vlc_sem_t;
620 * Initializes a semaphore.
622 * @param count initial semaphore value (typically 0)
624 VLC_API void vlc_sem_init(vlc_sem_t *, unsigned count);
627 * Increments the value of a semaphore.
629 * \note This function is not a cancellation point.
631 * \return 0 on success, EOVERFLOW in case of integer overflow.
633 VLC_API int vlc_sem_post(vlc_sem_t *);
636 * Waits on a semaphore.
638 * This function atomically waits for the semaphore to become non-zero then
639 * decrements it, and returns. If the semaphore is non-zero on entry, it is
640 * immediately decremented.
642 * \note This function may be a point of cancellation.
644 VLC_API void vlc_sem_wait(vlc_sem_t *);
647 * Waits on a semaphore within a deadline.
649 * This function waits for the semaphore just like vlc_sem_wait(), but only
650 * up to a given deadline.
652 * \param sem semaphore to wait for
653 * \param deadline deadline to wait until
655 * \retval 0 the semaphore was decremented
656 * \retval ETIMEDOUT the deadline was reached
658 VLC_API int vlc_sem_timedwait(vlc_sem_t *sem, vlc_tick_t deadline) VLC_USED;
660 /** @} */
663 * \defgroup rwlock Read/write locks
665 * Read/write locks are a type of thread synchronization primitive meant to
666 * protect access to data that is mostly read, and rarely written.
667 * As long as no threads tries to acquire the lock for "writing", any number of
668 * threads can acquire the lock for "reading".
670 * See also POSIX @c pthread_rwlock_t .
672 * @{
675 #ifdef LIBVLC_NEED_RWLOCK
676 typedef struct vlc_rwlock
678 vlc_mutex_t mutex;
679 vlc_cond_t wait;
680 long state;
681 } vlc_rwlock_t;
682 # define VLC_STATIC_RWLOCK { VLC_STATIC_MUTEX, VLC_STATIC_COND, 0 }
683 #endif
686 * Initializes a read/write lock.
688 * After use, a read/write lock must be deinitialized with
689 * vlc_rwlock_destroy().
691 VLC_API void vlc_rwlock_init(vlc_rwlock_t *);
694 * Destroys an initialized unused read/write lock.
696 VLC_API void vlc_rwlock_destroy(vlc_rwlock_t *);
699 * Acquires a read/write lock for reading.
701 * \note Recursion is allowed.
702 * \note This function may be a point of cancellation.
704 VLC_API void vlc_rwlock_rdlock(vlc_rwlock_t *);
707 * Acquires a read/write lock for writing. Recursion is not allowed.
708 * \note This function may be a point of cancellation.
710 VLC_API void vlc_rwlock_wrlock(vlc_rwlock_t *);
713 * Releases a read/write lock.
715 * The calling thread must hold the lock. Otherwise behaviour is undefined.
717 * \note This function is not a cancellation point.
719 VLC_API void vlc_rwlock_unlock(vlc_rwlock_t *);
721 /** @} */
724 * Executes a function one time.
726 * The first time this function is called with a given one-time initialization
727 * object, it executes the provided callback.
728 * Any further call with the same object will be a no-op.
730 * In the corner case that the first time execution is ongoing in another
731 * thread, then the function will wait for completion on the other thread
732 * (and then synchronize memory) before it returns.
733 * This ensures that, no matter what, the callback has been executed exactly
734 * once and its side effects are visible after the function returns.
736 * \param once a one-time initialization object
737 * \param cb callback to execute (the first time)
739 VLC_API void vlc_once(vlc_once_t *restrict once, void (*cb)(void));
742 * \defgroup threadvar Thread-specific variables
743 * @{
746 * Allocates a thread-specific variable.
748 * @param key where to store the thread-specific variable handle
749 * @param destr a destruction callback. It is called whenever a thread exits
750 * and the thread-specific variable has a non-NULL value.
752 * @return 0 on success, a system error code otherwise.
753 * This function can actually fail: on most systems, there is a fixed limit to
754 * the number of thread-specific variables in a given process.
756 VLC_API int vlc_threadvar_create(vlc_threadvar_t *key, void (*destr) (void *));
759 * Deallocates a thread-specific variable.
761 VLC_API void vlc_threadvar_delete(vlc_threadvar_t *);
764 * Sets a thread-specific variable.
766 * \param key thread-local variable key (created with vlc_threadvar_create())
767 * \param value new value for the variable for the calling thread
768 * \return 0 on success, a system error code otherwise.
770 VLC_API int vlc_threadvar_set(vlc_threadvar_t key, void *value);
773 * Gets the value of a thread-local variable for the calling thread.
774 * This function cannot fail.
776 * \return the value associated with the given variable for the calling
777 * or NULL if no value was set.
779 VLC_API void *vlc_threadvar_get(vlc_threadvar_t);
781 /** @} */
784 * Waits on an address.
786 * Puts the calling thread to sleep if a specific unsigned 32-bits value is
787 * stored at a specified address. The thread will sleep until it is woken up by
788 * a call to vlc_atomic_notify_one() or vlc_atomic_notify_all() in another
789 * thread, or spuriously.
791 * If the value does not match, do nothing and return immediately.
793 * \param addr address to check for
794 * \param val value to match at the address
796 void vlc_atomic_wait(void *addr, unsigned val);
799 * Waits on an address with a time-out.
801 * This function operates as vlc_atomic_wait() but provides an additional
802 * time-out. If the deadline is reached, the thread resumes and the function
803 * returns.
805 * \param addr address to check for
806 * \param val value to match at the address
807 * \param deadline deadline to wait until
809 * \retval 0 the function was woken up before the time-out
810 * \retval ETIMEDOUT the deadline was reached
812 int vlc_atomic_timedwait(void *addr, unsigned val, vlc_tick_t deadline);
815 * Wakes up one thread on an address.
817 * Wakes up (at least) one of the thread sleeping on the specified address.
818 * The address must be equal to the first parameter given by at least one
819 * thread sleeping within the vlc_atomic_wait() or vlc_atomic_timedwait()
820 * functions. If no threads are found, this function does nothing.
822 * \param addr address identifying which threads may be woken up
824 void vlc_atomic_notify_one(void *addr);
827 * Wakes up all thread on an address.
829 * Wakes up all threads sleeping on the specified address (if any).
830 * Any thread sleeping within a call to vlc_atomic_wait() or
831 * vlc_atomic_timedwait() with the specified address as first call parameter
832 * will be woken up.
834 * \param addr address identifying which threads to wake up
836 void vlc_atomic_notify_all(void *addr);
839 * Creates and starts a new thread.
841 * The thread must be <i>joined</i> with vlc_join() to reclaim resources
842 * when it is not needed anymore.
844 * @param th storage space for the handle of the new thread (cannot be NULL)
845 * [OUT]
846 * @param entry entry point for the thread
847 * @param data data parameter given to the entry point
848 * @param priority thread priority value
849 * @return 0 on success, a standard error code on error.
850 * @note In case of error, the value of *th is undefined.
852 VLC_API int vlc_clone(vlc_thread_t *th, void *(*entry)(void *), void *data,
853 int priority) VLC_USED;
856 * Marks a thread as cancelled.
858 * Next time the target thread reaches a cancellation point (while not having
859 * disabled cancellation), it will run its cancellation cleanup handler, the
860 * thread variable destructors, and terminate.
862 * vlc_join() must be used regardless of a thread being cancelled or not, to
863 * avoid leaking resources.
865 VLC_API void vlc_cancel(vlc_thread_t);
868 * Waits for a thread to complete (if needed), then destroys it.
870 * \note This is a cancellation point. In case of cancellation, the thread is
871 * <b>not</b> joined.
873 * \warning A thread cannot join itself (normally VLC will abort if this is
874 * attempted). Also a detached thread <b>cannot</b> be joined.
876 * @param th thread handle
877 * @param result [OUT] pointer to write the thread return value or NULL
879 VLC_API void vlc_join(vlc_thread_t th, void **result);
882 * Disables thread cancellation.
884 * This functions saves the current cancellation state (enabled or disabled),
885 * then disables cancellation for the calling thread. It must be called before
886 * entering a piece of code that is not cancellation-safe, unless it can be
887 * proven that the calling thread will not be cancelled.
889 * \note This function is not a cancellation point.
891 * \return Previous cancellation state (opaque value for vlc_restorecancel()).
893 VLC_API int vlc_savecancel(void);
896 * Restores the cancellation state.
898 * This function restores the cancellation state of the calling thread to
899 * a state previously saved by vlc_savecancel().
901 * \note This function is not a cancellation point.
903 * \param state previous state as returned by vlc_savecancel().
905 VLC_API void vlc_restorecancel(int state);
907 typedef struct vlc_cleanup_t vlc_cleanup_t;
910 * Internal handler for thread cancellation.
912 * Do not call this function directly. Use wrapper macros instead:
913 * vlc_cleanup_push(), vlc_cleanup_pop().
915 VLC_API void vlc_control_cancel(vlc_cleanup_t *);
918 * Thread handle.
920 * This function returns the thread handle of the calling thread.
921 * This works even if the thread was <b>not</b> created with vlc_clone().
922 * As a consequence, depending on the platform, this might or might not be the
923 * same as the @ref vlc_thread_t thread handle returned by vlc_clone().
925 * Also depending on the platform, this might be an integer type, a pointer
926 * type, or a compound type of any (reasonable) size. To compare two thread
927 * handles, use the vlc_thread_equal() macro, not a hand-coded comparison.
928 * Comparing the calling thread for equality with another thread is in fact
929 * pretty much the only purpose of this function.
931 * \note If you need an integer identifier, use vlc_thread_id() instead.
933 * \return the OS run-time thread handle
935 VLC_API vlc_osthread_t vlc_thread_self(void) VLC_USED;
938 * Thread identifier.
940 * This function returns the identifier of the calling thread. The identifier
941 * cannot change for the entire duration of the thread, and no other thread can
942 * have the same identifier at the same time in the same process. Typically,
943 * the identifier is also unique across all running threads of all existing
944 * processes, but that depends on the operating system.
946 * There are no particular semantics to the thread ID with LibVLC.
947 * It is provided mainly for tracing and debugging.
949 * See also vlc_thread_self().
951 * \warning This function is not currently implemented on all supported
952 * platforms. Where not implemented, it returns (unsigned long)-1.
954 * \return the thread identifier (or -1 if unimplemented)
956 VLC_API unsigned long vlc_thread_id(void) VLC_USED;
959 * Precision monotonic clock.
961 * In principles, the clock has a precision of 1 MHz. But the actual resolution
962 * may be much lower, especially when it comes to sleeping with vlc_tick_wait() or
963 * vlc_tick_sleep(). Most general-purpose operating systems provide a resolution of
964 * only 100 to 1000 Hz.
966 * \warning The origin date (time value "zero") is not specified. It is
967 * typically the time the kernel started, but this is platform-dependent.
968 * If you need wall clock time, use gettimeofday() instead.
970 * \return a timestamp in microseconds.
972 VLC_API vlc_tick_t vlc_tick_now(void);
975 * Waits until a deadline.
977 * \param deadline timestamp to wait for (\ref vlc_tick_now())
979 * \note The deadline may be exceeded due to OS scheduling.
980 * \note This function is a cancellation point.
982 VLC_API void vlc_tick_wait(vlc_tick_t deadline);
985 * Waits for an interval of time.
987 * \param delay how long to wait (in microseconds)
989 * \note The delay may be exceeded due to OS scheduling.
990 * \note This function is a cancellation point.
992 VLC_API void vlc_tick_sleep(vlc_tick_t delay);
994 #define VLC_HARD_MIN_SLEEP VLC_TICK_FROM_MS(10) /* 10 milliseconds = 1 tick at 100Hz */
995 #define VLC_SOFT_MIN_SLEEP VLC_TICK_FROM_SEC(9) /* 9 seconds */
997 #if defined (__GNUC__) && !defined (__clang__)
998 /* Linux has 100, 250, 300 or 1000Hz
1000 * HZ=100 by default on FreeBSD, but some architectures use a 1000Hz timer
1003 static
1004 __attribute__((unused))
1005 __attribute__((noinline))
1006 __attribute__((error("sorry, cannot sleep for such short a time")))
1007 vlc_tick_t impossible_delay( vlc_tick_t delay )
1009 (void) delay;
1010 return VLC_HARD_MIN_SLEEP;
1013 static
1014 __attribute__((unused))
1015 __attribute__((noinline))
1016 __attribute__((warning("use proper event handling instead of short delay")))
1017 vlc_tick_t harmful_delay( vlc_tick_t delay )
1019 return delay;
1022 # define check_delay( d ) \
1023 ((__builtin_constant_p(d < VLC_HARD_MIN_SLEEP) \
1024 && (d < VLC_HARD_MIN_SLEEP)) \
1025 ? impossible_delay(d) \
1026 : ((__builtin_constant_p(d < VLC_SOFT_MIN_SLEEP) \
1027 && (d < VLC_SOFT_MIN_SLEEP)) \
1028 ? harmful_delay(d) \
1029 : d))
1031 static
1032 __attribute__((unused))
1033 __attribute__((noinline))
1034 __attribute__((error("deadlines can not be constant")))
1035 vlc_tick_t impossible_deadline( vlc_tick_t deadline )
1037 return deadline;
1040 # define check_deadline( d ) \
1041 (__builtin_constant_p(d) ? impossible_deadline(d) : d)
1042 #else
1043 # define check_delay(d) (d)
1044 # define check_deadline(d) (d)
1045 #endif
1047 #define vlc_tick_sleep(d) vlc_tick_sleep(check_delay(d))
1048 #define vlc_tick_wait(d) vlc_tick_wait(check_deadline(d))
1051 * \defgroup timer Asynchronous/threaded timers
1052 * @{
1055 * Initializes an asynchronous timer.
1057 * \param id pointer to timer to be initialized
1058 * \param func function that the timer will call
1059 * \param data parameter for the timer function
1060 * \return 0 on success, a system error code otherwise.
1062 * \warning Asynchronous timers are processed from an unspecified thread.
1063 * \note Multiple occurrences of a single interval timer are serialized:
1064 * they cannot run concurrently.
1066 VLC_API int vlc_timer_create(vlc_timer_t *id, void (*func)(void *), void *data)
1067 VLC_USED;
1070 * Destroys an initialized timer.
1072 * If needed, the timer is first disarmed. Behaviour is undefined if the
1073 * specified timer is not initialized.
1075 * \warning This function <b>must</b> be called before the timer data can be
1076 * freed and before the timer callback function can be unmapped/unloaded.
1078 * \param timer timer to destroy
1080 VLC_API void vlc_timer_destroy(vlc_timer_t timer);
1082 #define VLC_TIMER_DISARM (0)
1083 #define VLC_TIMER_FIRE_ONCE (0)
1086 * Arms or disarms an initialized timer.
1088 * This functions overrides any previous call to itself.
1090 * \note A timer can fire later than requested due to system scheduling
1091 * limitations. An interval timer can fail to trigger sometimes, either because
1092 * the system is busy or suspended, or because a previous iteration of the
1093 * timer is still running. See also vlc_timer_getoverrun().
1095 * \param timer initialized timer
1096 * \param absolute the timer value origin is the same as vlc_tick_now() if true,
1097 * the timer value is relative to now if false.
1098 * \param value zero to disarm the timer, otherwise the initial time to wait
1099 * before firing the timer.
1100 * \param interval zero to fire the timer just once, otherwise the timer
1101 * repetition interval.
1103 VLC_API void vlc_timer_schedule(vlc_timer_t timer, bool absolute,
1104 vlc_tick_t value, vlc_tick_t interval);
1106 static inline void vlc_timer_disarm(vlc_timer_t timer)
1108 vlc_timer_schedule( timer, false, VLC_TIMER_DISARM, 0 );
1111 static inline void vlc_timer_schedule_asap(vlc_timer_t timer, vlc_tick_t interval)
1113 vlc_timer_schedule(timer, false, 1, interval);
1117 * Fetches and resets the overrun counter for a timer.
1119 * This functions returns the number of times that the interval timer should
1120 * have fired, but the callback was not invoked due to scheduling problems.
1121 * The call resets the counter to zero.
1123 * \param timer initialized timer
1124 * \return the timer overrun counter (typically zero)
1126 VLC_API unsigned vlc_timer_getoverrun(vlc_timer_t) VLC_USED;
1128 /** @} */
1131 * Count CPUs.
1133 * \return number of available (logical) CPUs.
1135 VLC_API unsigned vlc_GetCPUCount(void);
1137 #if defined (LIBVLC_USE_PTHREAD_CLEANUP)
1139 * Registers a thread cancellation handler.
1141 * This pushes a function to run if the thread is cancelled (or otherwise
1142 * exits prematurely).
1144 * If multiple procedures are registered,
1145 * they are handled in last-in first-out order.
1147 * \note Any call to vlc_cleanup_push() <b>must</b> paired with a call to
1148 * vlc_cleanup_pop().
1149 * \warning Branching into or out of the block between these two function calls
1150 * is not allowed (read: it will likely crash the whole process).
1152 * \param routine procedure to call if the thread ends
1153 * \param arg argument for the procedure
1155 # define vlc_cleanup_push( routine, arg ) pthread_cleanup_push (routine, arg)
1158 * Unregisters the last cancellation handler.
1160 * This pops the cancellation handler that was last pushed with
1161 * vlc_cleanup_push() in the calling thread.
1163 # define vlc_cleanup_pop( ) pthread_cleanup_pop (0)
1165 #else /* !LIBVLC_USE_PTHREAD_CLEANUP */
1166 struct vlc_cleanup_t
1168 vlc_cleanup_t *next;
1169 void (*proc) (void *);
1170 void *data;
1173 # ifndef __cplusplus
1174 /* This macros opens a code block on purpose: It reduces the chance of
1175 * not pairing the push and pop. It also matches the POSIX Thread internals.
1176 * That way, Win32 developers will not accidentally break other platforms.
1178 # define vlc_cleanup_push( routine, arg ) \
1179 do { \
1180 vlc_control_cancel(&(vlc_cleanup_t){ NULL, routine, arg })
1182 # define vlc_cleanup_pop( ) \
1183 vlc_control_cancel (NULL); \
1184 } while (0)
1185 # else
1186 # define vlc_cleanup_push(routine, arg) \
1187 static_assert(false, "don't use vlc_cleanup_push in portable C++ code")
1188 # define vlc_cleanup_pop() \
1189 static_assert(false, "don't use vlc_cleanup_pop in portable C++ code")
1190 # endif
1192 #endif /* !LIBVLC_USE_PTHREAD_CLEANUP */
1194 static inline void vlc_cleanup_lock (void *lock)
1196 vlc_mutex_unlock ((vlc_mutex_t *)lock);
1198 #define mutex_cleanup_push( lock ) vlc_cleanup_push (vlc_cleanup_lock, lock)
1200 #if defined(LIBVLC_NEED_CONDVAR) && !defined(__cplusplus)
1201 void vlc_cancel_addr_set(atomic_uint *addr);
1202 void vlc_cancel_addr_clear(atomic_uint *addr);
1203 #endif
1205 #ifdef __cplusplus
1207 * Helper C++ class to lock a mutex.
1209 * The mutex is locked when the object is created, and unlocked when the object
1210 * is destroyed.
1212 class vlc_mutex_locker
1214 private:
1215 vlc_mutex_t *lock;
1216 public:
1217 vlc_mutex_locker (vlc_mutex_t *m) : lock (m)
1219 vlc_mutex_lock (lock);
1222 ~vlc_mutex_locker (void)
1224 vlc_mutex_unlock (lock);
1228 #endif
1230 enum
1232 VLC_AVCODEC_MUTEX = 0,
1233 VLC_GCRYPT_MUTEX,
1234 VLC_XLIB_MUTEX,
1235 VLC_MOSAIC_MUTEX,
1236 #ifdef _WIN32
1237 VLC_MTA_MUTEX,
1238 #endif
1239 /* Insert new entry HERE */
1240 VLC_MAX_MUTEX
1244 * Internal handler for global mutexes.
1246 * Do not use this function directly. Use helper macros instead:
1247 * vlc_global_lock(), vlc_global_unlock().
1249 VLC_API void vlc_global_mutex(unsigned, bool);
1252 * Acquires a global mutex.
1254 #define vlc_global_lock( n ) vlc_global_mutex(n, true)
1257 * Releases a global mutex.
1259 #define vlc_global_unlock( n ) vlc_global_mutex(n, false)
1261 /** @} */
1263 #endif /* !_VLC_THREADS_H */