input: add input_SetProgramId
[vlc.git] / include / vlc_threads.h
bloba333f0cd14e0873a85696154844c1f7fc5e3c344
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 # define LIBVLC_NEED_SLEEP
63 typedef struct vlc_threadvar *vlc_threadvar_t;
64 typedef struct vlc_timer *vlc_timer_t;
66 # define VLC_THREAD_PRIORITY_LOW 0
67 # define VLC_THREAD_PRIORITY_INPUT THREAD_PRIORITY_ABOVE_NORMAL
68 # define VLC_THREAD_PRIORITY_AUDIO THREAD_PRIORITY_HIGHEST
69 # define VLC_THREAD_PRIORITY_VIDEO 0
70 # define VLC_THREAD_PRIORITY_OUTPUT THREAD_PRIORITY_ABOVE_NORMAL
71 # define VLC_THREAD_PRIORITY_HIGHEST THREAD_PRIORITY_TIME_CRITICAL
73 static inline int vlc_poll(struct pollfd *fds, unsigned nfds, int timeout)
75 int val;
77 vlc_testcancel();
78 val = poll(fds, nfds, timeout);
79 if (val < 0)
80 vlc_testcancel();
81 return val;
83 # define poll(u,n,t) vlc_poll(u, n, t)
85 #elif defined (__OS2__)
86 # include <errno.h>
88 typedef struct vlc_thread *vlc_thread_t;
89 #define VLC_THREAD_CANCELED NULL
91 typedef struct vlc_threadvar *vlc_threadvar_t;
92 typedef struct vlc_timer *vlc_timer_t;
94 # define VLC_THREAD_PRIORITY_LOW 0
95 # define VLC_THREAD_PRIORITY_INPUT 1
96 # define VLC_THREAD_PRIORITY_AUDIO VLC_THREAD_PRIORITY_HIGHEST
97 # define VLC_THREAD_PRIORITY_VIDEO 0
98 # define VLC_THREAD_PRIORITY_OUTPUT 1
99 # define VLC_THREAD_PRIORITY_HIGHEST 2
101 # define pthread_sigmask sigprocmask
103 static inline int vlc_poll (struct pollfd *fds, unsigned nfds, int timeout)
105 static int (*vlc_poll_os2)(struct pollfd *, unsigned, int) = NULL;
107 if (!vlc_poll_os2)
109 HMODULE hmod;
110 CHAR szFailed[CCHMAXPATH];
112 if (DosLoadModule(szFailed, sizeof(szFailed), "vlccore", &hmod))
113 return -1;
115 if (DosQueryProcAddr(hmod, 0, "_vlc_poll_os2", (PFN *)&vlc_poll_os2))
116 return -1;
119 return (*vlc_poll_os2)(fds, nfds, timeout);
121 # define poll(u,n,t) vlc_poll(u, n, t)
123 #elif defined (__ANDROID__) /* pthreads subset without pthread_cancel() */
124 # include <unistd.h>
125 # include <pthread.h>
126 # include <poll.h>
127 # define LIBVLC_USE_PTHREAD_CLEANUP 1
128 # define LIBVLC_NEED_SLEEP
130 typedef struct vlc_thread *vlc_thread_t;
131 #define VLC_THREAD_CANCELED NULL
132 typedef pthread_key_t vlc_threadvar_t;
133 typedef struct vlc_timer *vlc_timer_t;
135 # define VLC_THREAD_PRIORITY_LOW 0
136 # define VLC_THREAD_PRIORITY_INPUT 0
137 # define VLC_THREAD_PRIORITY_AUDIO 0
138 # define VLC_THREAD_PRIORITY_VIDEO 0
139 # define VLC_THREAD_PRIORITY_OUTPUT 0
140 # define VLC_THREAD_PRIORITY_HIGHEST 0
142 static inline int vlc_poll (struct pollfd *fds, unsigned nfds, int timeout)
144 int val;
148 int ugly_timeout = ((unsigned)timeout >= 50) ? 50 : timeout;
149 if (timeout >= 0)
150 timeout -= ugly_timeout;
152 vlc_testcancel ();
153 val = poll (fds, nfds, ugly_timeout);
155 while (val == 0 && timeout != 0);
157 return val;
160 # define poll(u,n,t) vlc_poll(u, n, t)
162 #else /* POSIX threads */
163 # include <unistd.h> /* _POSIX_SPIN_LOCKS */
164 # include <pthread.h>
167 * Whether LibVLC threads are based on POSIX threads.
169 # define LIBVLC_USE_PTHREAD 1
172 * Whether LibVLC thread cancellation is based on POSIX threads.
174 # define LIBVLC_USE_PTHREAD_CLEANUP 1
177 * Thread handle.
179 typedef struct
181 pthread_t handle;
182 } vlc_thread_t;
185 * Return value of a canceled thread.
187 #define VLC_THREAD_CANCELED PTHREAD_CANCELED
190 * Thread-local key handle.
192 * \ingroup threadvar
194 typedef pthread_key_t vlc_threadvar_t;
197 * Threaded timer handle.
199 * \ingroup timer
201 typedef struct vlc_timer *vlc_timer_t;
203 /* Thread priorities.
204 * No effect for POSIX threads
206 # define VLC_THREAD_PRIORITY_LOW 0
207 # define VLC_THREAD_PRIORITY_INPUT 0
208 # define VLC_THREAD_PRIORITY_AUDIO 0
209 # define VLC_THREAD_PRIORITY_VIDEO 0
210 # define VLC_THREAD_PRIORITY_OUTPUT 0
211 # define VLC_THREAD_PRIORITY_HIGHEST 0
213 #endif
216 * \defgroup mutex Mutual exclusion locks
217 * @{
220 * Mutex.
222 * Storage space for a mutual exclusion lock.
224 typedef struct
226 union {
227 #ifndef __cplusplus
228 struct {
229 atomic_uint value;
230 atomic_uint recursion;
231 _Atomic (const void *) owner;
233 #endif
234 struct {
235 unsigned int value;
236 unsigned int recursion;
237 const void *owner;
238 } dummy;
240 } vlc_mutex_t;
243 * Static initializer for (static) mutex.
245 * \note This only works in C code.
246 * In C++, consider using a global \ref vlc::threads::mutex instance instead.
248 #define VLC_STATIC_MUTEX { \
249 .value = ATOMIC_VAR_INIT(0), \
250 .recursion = ATOMIC_VAR_INIT(0), \
251 .owner = ATOMIC_VAR_INIT(NULL), \
255 * Initializes a fast mutex.
257 * Recursive locking of a fast mutex is undefined behaviour. (In debug builds,
258 * recursive locking will cause an assertion failure.)
260 VLC_API void vlc_mutex_init(vlc_mutex_t *);
263 * Initializes a recursive mutex.
264 * \warning This is strongly discouraged. Please use normal mutexes.
266 VLC_API void vlc_mutex_init_recursive(vlc_mutex_t *);
269 * Acquires a mutex.
271 * If needed, this waits for any other thread to release it.
273 * \warning Beware of deadlocks when locking multiple mutexes at the same time,
274 * or when using mutexes from callbacks.
276 * \note This function is not a cancellation point.
278 VLC_API void vlc_mutex_lock(vlc_mutex_t *);
281 * Tries to acquire a mutex.
283 * This function acquires the mutex if and only if it is not currently held by
284 * another thread. This function never sleeps and can be used in delay-critical
285 * code paths.
287 * \note This function is not a cancellation point.
289 * \warning If this function fails, then the mutex is held... by another
290 * thread. The calling thread must deal with the error appropriately. That
291 * typically implies postponing the operations that would have required the
292 * mutex. If the thread cannot defer those operations, then it must use
293 * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
295 * @return 0 if the mutex could be acquired, an error code otherwise.
297 VLC_API int vlc_mutex_trylock( vlc_mutex_t * ) VLC_USED;
300 * Releases a mutex.
302 * If the mutex is not held by the calling thread, the behaviour is undefined.
304 * \note This function is not a cancellation point.
306 VLC_API void vlc_mutex_unlock(vlc_mutex_t *);
309 * Checks if a mutex is locked.
311 * Do not use this function directly. Use vlc_mutex_assert() instead.
313 * @note
314 * This function has no effects.
315 * It is only meant to be use in run-time assertions.
317 * @warning This function might not return correct results in non-debug builds.
319 * @retval false the mutex is not locked by the calling thread
320 * @retval true the mutex is locked by the calling thread
322 VLC_API bool vlc_mutex_held(const vlc_mutex_t *) VLC_USED;
325 * Asserts that a mutex is locked by the calling thread.
327 #define vlc_mutex_assert(m) assert(vlc_mutex_held(m))
329 /** @} */
332 * \defgroup condvar Condition variables
334 * The condition variable is the most common and generic mean for threads to
335 * wait for events triggered by other threads.
337 * See also POSIX @c pthread_cond_t .
338 * @{
341 struct vlc_cond_waiter;
344 * Condition variable.
346 * Storage space for a thread condition variable.
348 typedef struct
350 struct vlc_cond_waiter *head;
351 vlc_mutex_t lock;
352 } vlc_cond_t;
355 * Static initializer for (static) condition variable.
357 #define VLC_STATIC_COND { NULL, VLC_STATIC_MUTEX }
360 * Initializes a condition variable.
362 VLC_API void vlc_cond_init(vlc_cond_t *);
365 * Wakes up one thread waiting on a condition variable.
367 * If any thread is currently waiting on the condition variable, at least one
368 * of those threads will be woken up. Otherwise, this function has no effects.
370 * \note This function is not a cancellation point.
372 VLC_API void vlc_cond_signal(vlc_cond_t *);
375 * Wakes up all threads waiting on a condition variable.
377 * \note This function is not a cancellation point.
379 VLC_API void vlc_cond_broadcast(vlc_cond_t *);
382 * Waits on a condition variable.
384 * The calling thread will be suspended until another thread calls
385 * vlc_cond_signal() or vlc_cond_broadcast() on the same condition variable,
386 * the thread is cancelled with vlc_cancel(), or the system causes a
387 * <em>spurious</em> unsolicited wake-up.
389 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
390 * a recursive mutex. Although it is possible to use the same mutex for
391 * multiple condition, it is not valid to use different mutexes for the same
392 * condition variable at the same time from different threads.
394 * The canonical way to use a condition variable to wait for event foobar is:
395 @code
396 vlc_mutex_lock(&lock);
398 while (!foobar)
399 vlc_cond_wait(&wait, &lock);
401 // -- foobar is now true, do something about it here --
403 vlc_mutex_unlock(&lock);
404 @endcode
406 * \param cond condition variable to wait on
407 * \param mutex mutex which is unlocked while waiting,
408 * then locked again when waking up.
410 VLC_API void vlc_cond_wait(vlc_cond_t *cond, vlc_mutex_t *mutex);
413 * Waits on a condition variable up to a certain date.
415 * This works like vlc_cond_wait() but with an additional time-out.
416 * The time-out is expressed as an absolute timestamp using the same arbitrary
417 * time reference as the vlc_tick_now() and vlc_tick_wait() functions.
419 * \param cond condition variable to wait on
420 * \param mutex mutex which is unlocked while waiting,
421 * then locked again when waking up
422 * \param deadline <b>absolute</b> timeout
424 * \return 0 if the condition was signaled, an error code in case of timeout.
426 VLC_API int vlc_cond_timedwait(vlc_cond_t *cond, vlc_mutex_t *mutex,
427 vlc_tick_t deadline);
429 int vlc_cond_timedwait_daytime(vlc_cond_t *, vlc_mutex_t *, time_t);
431 /** @} */
434 * \defgroup semaphore Semaphores
436 * The semaphore is the simplest thread synchronization primitive, consisting
437 * of a simple counter.
439 * See also POSIX @c sem_t .
441 * @{
444 * Semaphore.
446 * Storage space for a thread-safe semaphore.
448 typedef struct
450 union {
451 #ifndef __cplusplus
452 atomic_uint value;
453 #endif
454 int dummy;
456 } vlc_sem_t;
459 * Initializes a semaphore.
461 * @param count initial semaphore value (typically 0)
463 VLC_API void vlc_sem_init(vlc_sem_t *, unsigned count);
466 * Increments the value of a semaphore.
468 * \note This function is not a cancellation point.
470 * \return 0 on success, EOVERFLOW in case of integer overflow.
472 VLC_API int vlc_sem_post(vlc_sem_t *);
475 * Waits on a semaphore.
477 * This function atomically waits for the semaphore to become non-zero then
478 * decrements it, and returns. If the semaphore is non-zero on entry, it is
479 * immediately decremented.
481 * \note This function may be a point of cancellation.
483 VLC_API void vlc_sem_wait(vlc_sem_t *);
486 * Tries to decrement a semaphore.
488 * This function decrements the semaphore if its value is not zero.
490 * \param sem semaphore to decrement
492 * \retval 0 the semaphore was decremented
493 * \retval EAGAIN the semaphore was zero and could not be decremented
495 VLC_API int vlc_sem_trywait(vlc_sem_t *sem) VLC_USED;
498 * Waits on a semaphore within a deadline.
500 * This function waits for the semaphore just like vlc_sem_wait(), but only
501 * up to a given deadline.
503 * \param sem semaphore to wait for
504 * \param deadline deadline to wait until
506 * \retval 0 the semaphore was decremented
507 * \retval ETIMEDOUT the deadline was reached
509 VLC_API int vlc_sem_timedwait(vlc_sem_t *sem, vlc_tick_t deadline) VLC_USED;
511 /** @} */
514 * \defgroup rwlock Read/write locks
516 * Read/write locks are a type of thread synchronization primitive meant to
517 * protect access to data that is mostly read, and rarely written.
518 * As long as no threads tries to acquire the lock for "writing", any number of
519 * threads can acquire the lock for "reading".
521 * See also POSIX @c pthread_rwlock_t .
523 * @{
527 * Read/write lock.
529 * Storage space for a slim reader/writer lock.
531 typedef struct vlc_rwlock
533 vlc_mutex_t mutex;
534 vlc_cond_t wait;
535 long state;
536 } vlc_rwlock_t;
539 * Static initializer for (static) read/write lock.
541 #define VLC_STATIC_RWLOCK { VLC_STATIC_MUTEX, VLC_STATIC_COND, 0 }
544 * Initializes a read/write lock.
546 VLC_API void vlc_rwlock_init(vlc_rwlock_t *);
549 * Acquires a read/write lock for reading.
551 * \note Recursion is allowed.
553 VLC_API void vlc_rwlock_rdlock(vlc_rwlock_t *);
556 * Acquires a read/write lock for writing. Recursion is not allowed.
558 VLC_API void vlc_rwlock_wrlock(vlc_rwlock_t *);
561 * Releases a read/write lock.
563 * The calling thread must hold the lock. Otherwise behaviour is undefined.
565 * \note This function is not a cancellation point.
567 VLC_API void vlc_rwlock_unlock(vlc_rwlock_t *);
569 /** @} */
571 #ifndef __cplusplus
573 * One-time initialization.
575 * A one-time initialization object must always be initialized assigned to
576 * \ref VLC_STATIC_ONCE before use.
578 typedef struct
580 atomic_uint value;
581 } vlc_once_t;
584 * Static initializer for one-time initialization.
586 #define VLC_STATIC_ONCE { ATOMIC_VAR_INIT(0) }
589 * Executes a function one time.
591 * The first time this function is called with a given one-time initialization
592 * object, it executes the provided callback.
593 * Any further call with the same object will be a no-op.
595 * In the corner case that the first time execution is ongoing in another
596 * thread, then the function will wait for completion on the other thread
597 * (and then synchronize memory) before it returns.
598 * This ensures that, no matter what, the callback has been executed exactly
599 * once and its side effects are visible after the function returns.
601 * \param once a one-time initialization object
602 * \param cb callback to execute (the first time)
604 VLC_API void vlc_once(vlc_once_t *restrict once, void (*cb)(void));
606 static inline void vlc_once_inline(vlc_once_t *restrict once, void (*cb)(void))
608 /* Fast path: check if already initialized */
609 if (unlikely(atomic_load_explicit(&once->value, memory_order_acquire) < 3))
610 vlc_once(once, cb);
612 #define vlc_once(once, cb) vlc_once_inline(once, cb)
613 #endif
616 * \defgroup threadvar Thread-specific variables
617 * @{
620 * Allocates a thread-specific variable.
622 * @param key where to store the thread-specific variable handle
623 * @param destr a destruction callback. It is called whenever a thread exits
624 * and the thread-specific variable has a non-NULL value.
626 * @return 0 on success, a system error code otherwise.
627 * This function can actually fail: on most systems, there is a fixed limit to
628 * the number of thread-specific variables in a given process.
630 VLC_API int vlc_threadvar_create(vlc_threadvar_t *key, void (*destr) (void *));
633 * Deallocates a thread-specific variable.
635 VLC_API void vlc_threadvar_delete(vlc_threadvar_t *);
638 * Sets a thread-specific variable.
640 * \param key thread-local variable key (created with vlc_threadvar_create())
641 * \param value new value for the variable for the calling thread
642 * \return 0 on success, a system error code otherwise.
644 VLC_API int vlc_threadvar_set(vlc_threadvar_t key, void *value);
647 * Gets the value of a thread-local variable for the calling thread.
648 * This function cannot fail.
650 * \return the value associated with the given variable for the calling
651 * or NULL if no value was set.
653 VLC_API void *vlc_threadvar_get(vlc_threadvar_t);
655 /** @} */
658 * Waits on an address.
660 * Puts the calling thread to sleep if a specific unsigned 32-bits value is
661 * stored at a specified address. The thread will sleep until it is woken up by
662 * a call to vlc_atomic_notify_one() or vlc_atomic_notify_all() in another
663 * thread, or spuriously.
665 * If the value does not match, do nothing and return immediately.
667 * \param addr address to check for
668 * \param val value to match at the address
670 void vlc_atomic_wait(void *addr, unsigned val);
673 * Waits on an address with a time-out.
675 * This function operates as vlc_atomic_wait() but provides an additional
676 * time-out. If the deadline is reached, the thread resumes and the function
677 * returns.
679 * \param addr address to check for
680 * \param val value to match at the address
681 * \param deadline deadline to wait until
683 * \retval 0 the function was woken up before the time-out
684 * \retval ETIMEDOUT the deadline was reached
686 int vlc_atomic_timedwait(void *addr, unsigned val, vlc_tick_t deadline);
688 int vlc_atomic_timedwait_daytime(void *addr, unsigned val, time_t deadline);
691 * Wakes up one thread on an address.
693 * Wakes up (at least) one of the thread sleeping on the specified address.
694 * The address must be equal to the first parameter given by at least one
695 * thread sleeping within the vlc_atomic_wait() or vlc_atomic_timedwait()
696 * functions. If no threads are found, this function does nothing.
698 * \param addr address identifying which threads may be woken up
700 void vlc_atomic_notify_one(void *addr);
703 * Wakes up all thread on an address.
705 * Wakes up all threads sleeping on the specified address (if any).
706 * Any thread sleeping within a call to vlc_atomic_wait() or
707 * vlc_atomic_timedwait() with the specified address as first call parameter
708 * will be woken up.
710 * \param addr address identifying which threads to wake up
712 void vlc_atomic_notify_all(void *addr);
715 * Creates and starts a new thread.
717 * The thread must be <i>joined</i> with vlc_join() to reclaim resources
718 * when it is not needed anymore.
720 * @param th storage space for the handle of the new thread (cannot be NULL)
721 * [OUT]
722 * @param entry entry point for the thread
723 * @param data data parameter given to the entry point
724 * @param priority thread priority value
725 * @return 0 on success, a standard error code on error.
726 * @note In case of error, the value of *th is undefined.
728 VLC_API int vlc_clone(vlc_thread_t *th, void *(*entry)(void *), void *data,
729 int priority) VLC_USED;
732 * Marks a thread as cancelled.
734 * Next time the target thread reaches a cancellation point (while not having
735 * disabled cancellation), it will run its cancellation cleanup handler, the
736 * thread variable destructors, and terminate.
738 * vlc_join() must be used regardless of a thread being cancelled or not, to
739 * avoid leaking resources.
741 VLC_API void vlc_cancel(vlc_thread_t);
744 * Waits for a thread to complete (if needed), then destroys it.
746 * \note This is a cancellation point. In case of cancellation, the thread is
747 * <b>not</b> joined.
749 * \warning A thread cannot join itself (normally VLC will abort if this is
750 * attempted). Also a detached thread <b>cannot</b> be joined.
752 * @param th thread handle
753 * @param result [OUT] pointer to write the thread return value or NULL
755 VLC_API void vlc_join(vlc_thread_t th, void **result);
758 * Disables thread cancellation.
760 * This functions saves the current cancellation state (enabled or disabled),
761 * then disables cancellation for the calling thread. It must be called before
762 * entering a piece of code that is not cancellation-safe, unless it can be
763 * proven that the calling thread will not be cancelled.
765 * \note This function is not a cancellation point.
767 * \return Previous cancellation state (opaque value for vlc_restorecancel()).
769 VLC_API int vlc_savecancel(void);
772 * Restores the cancellation state.
774 * This function restores the cancellation state of the calling thread to
775 * a state previously saved by vlc_savecancel().
777 * \note This function is not a cancellation point.
779 * \param state previous state as returned by vlc_savecancel().
781 VLC_API void vlc_restorecancel(int state);
783 typedef struct vlc_cleanup_t vlc_cleanup_t;
786 * Internal handler for thread cancellation.
788 * Do not call this function directly. Use wrapper macros instead:
789 * vlc_cleanup_push(), vlc_cleanup_pop().
791 VLC_API void vlc_control_cancel(vlc_cleanup_t *);
794 * Thread identifier.
796 * This function returns the identifier of the calling thread. The identifier
797 * cannot change for the entire duration of the thread, and no other thread can
798 * have the same identifier at the same time in the same process. Typically,
799 * the identifier is also unique across all running threads of all existing
800 * processes, but that depends on the operating system.
802 * There are no particular semantics to the thread ID with LibVLC.
803 * It is provided mainly for tracing and debugging.
805 * \warning This function is not currently implemented on all supported
806 * platforms. Where not implemented, it returns (unsigned long)-1.
808 * \return the thread identifier (or -1 if unimplemented)
810 VLC_API unsigned long vlc_thread_id(void) VLC_USED;
813 * Precision monotonic clock.
815 * In principles, the clock has a precision of 1 MHz. But the actual resolution
816 * may be much lower, especially when it comes to sleeping with vlc_tick_wait() or
817 * vlc_tick_sleep(). Most general-purpose operating systems provide a resolution of
818 * only 100 to 1000 Hz.
820 * \warning The origin date (time value "zero") is not specified. It is
821 * typically the time the kernel started, but this is platform-dependent.
822 * If you need wall clock time, use gettimeofday() instead.
824 * \return a timestamp in microseconds.
826 VLC_API vlc_tick_t vlc_tick_now(void);
829 * Waits until a deadline.
831 * \param deadline timestamp to wait for (\ref vlc_tick_now())
833 * \note The deadline may be exceeded due to OS scheduling.
834 * \note This function is a cancellation point.
836 VLC_API void vlc_tick_wait(vlc_tick_t deadline);
839 * Waits for an interval of time.
841 * \param delay how long to wait (in microseconds)
843 * \note The delay may be exceeded due to OS scheduling.
844 * \note This function is a cancellation point.
846 VLC_API void vlc_tick_sleep(vlc_tick_t delay);
848 #define VLC_HARD_MIN_SLEEP VLC_TICK_FROM_MS(10) /* 10 milliseconds = 1 tick at 100Hz */
849 #define VLC_SOFT_MIN_SLEEP VLC_TICK_FROM_SEC(9) /* 9 seconds */
851 #if defined (__GNUC__) && !defined (__clang__)
852 /* Linux has 100, 250, 300 or 1000Hz
854 * HZ=100 by default on FreeBSD, but some architectures use a 1000Hz timer
857 static
858 __attribute__((unused))
859 __attribute__((noinline))
860 __attribute__((error("sorry, cannot sleep for such short a time")))
861 vlc_tick_t impossible_delay( vlc_tick_t delay )
863 (void) delay;
864 return VLC_HARD_MIN_SLEEP;
867 static
868 __attribute__((unused))
869 __attribute__((noinline))
870 __attribute__((warning("use proper event handling instead of short delay")))
871 vlc_tick_t harmful_delay( vlc_tick_t delay )
873 return delay;
876 # define check_delay( d ) \
877 ((__builtin_constant_p(d < VLC_HARD_MIN_SLEEP) \
878 && (d < VLC_HARD_MIN_SLEEP)) \
879 ? impossible_delay(d) \
880 : ((__builtin_constant_p(d < VLC_SOFT_MIN_SLEEP) \
881 && (d < VLC_SOFT_MIN_SLEEP)) \
882 ? harmful_delay(d) \
883 : d))
885 static
886 __attribute__((unused))
887 __attribute__((noinline))
888 __attribute__((error("deadlines can not be constant")))
889 vlc_tick_t impossible_deadline( vlc_tick_t deadline )
891 return deadline;
894 # define check_deadline( d ) \
895 (__builtin_constant_p(d) ? impossible_deadline(d) : d)
896 #else
897 # define check_delay(d) (d)
898 # define check_deadline(d) (d)
899 #endif
901 #define vlc_tick_sleep(d) vlc_tick_sleep(check_delay(d))
902 #define vlc_tick_wait(d) vlc_tick_wait(check_deadline(d))
905 * \defgroup timer Asynchronous/threaded timers
906 * @{
909 * Initializes an asynchronous timer.
911 * \param id pointer to timer to be initialized
912 * \param func function that the timer will call
913 * \param data parameter for the timer function
914 * \return 0 on success, a system error code otherwise.
916 * \warning Asynchronous timers are processed from an unspecified thread.
917 * \note Multiple occurrences of a single interval timer are serialized:
918 * they cannot run concurrently.
920 VLC_API int vlc_timer_create(vlc_timer_t *id, void (*func)(void *), void *data)
921 VLC_USED;
924 * Destroys an initialized timer.
926 * If needed, the timer is first disarmed. Behaviour is undefined if the
927 * specified timer is not initialized.
929 * \warning This function <b>must</b> be called before the timer data can be
930 * freed and before the timer callback function can be unmapped/unloaded.
932 * \param timer timer to destroy
934 VLC_API void vlc_timer_destroy(vlc_timer_t timer);
936 #define VLC_TIMER_DISARM (0)
937 #define VLC_TIMER_FIRE_ONCE (0)
940 * Arms or disarms an initialized timer.
942 * This functions overrides any previous call to itself.
944 * \note A timer can fire later than requested due to system scheduling
945 * limitations. An interval timer can fail to trigger sometimes, either because
946 * the system is busy or suspended, or because a previous iteration of the
947 * timer is still running. See also vlc_timer_getoverrun().
949 * \param timer initialized timer
950 * \param absolute the timer value origin is the same as vlc_tick_now() if true,
951 * the timer value is relative to now if false.
952 * \param value zero to disarm the timer, otherwise the initial time to wait
953 * before firing the timer.
954 * \param interval zero to fire the timer just once, otherwise the timer
955 * repetition interval.
957 VLC_API void vlc_timer_schedule(vlc_timer_t timer, bool absolute,
958 vlc_tick_t value, vlc_tick_t interval);
960 static inline void vlc_timer_disarm(vlc_timer_t timer)
962 vlc_timer_schedule( timer, false, VLC_TIMER_DISARM, 0 );
965 static inline void vlc_timer_schedule_asap(vlc_timer_t timer, vlc_tick_t interval)
967 vlc_timer_schedule(timer, false, 1, interval);
971 * Fetches and resets the overrun counter for a timer.
973 * This functions returns the number of times that the interval timer should
974 * have fired, but the callback was not invoked due to scheduling problems.
975 * The call resets the counter to zero.
977 * \param timer initialized timer
978 * \return the timer overrun counter (typically zero)
980 VLC_API unsigned vlc_timer_getoverrun(vlc_timer_t) VLC_USED;
982 /** @} */
985 * Count CPUs.
987 * \return number of available (logical) CPUs.
989 VLC_API unsigned vlc_GetCPUCount(void);
991 #if defined (LIBVLC_USE_PTHREAD_CLEANUP)
993 * Registers a thread cancellation handler.
995 * This pushes a function to run if the thread is cancelled (or otherwise
996 * exits prematurely).
998 * If multiple procedures are registered,
999 * they are handled in last-in first-out order.
1001 * \note Any call to vlc_cleanup_push() <b>must</b> paired with a call to
1002 * vlc_cleanup_pop().
1003 * \warning Branching into or out of the block between these two function calls
1004 * is not allowed (read: it will likely crash the whole process).
1006 * \param routine procedure to call if the thread ends
1007 * \param arg argument for the procedure
1009 # define vlc_cleanup_push( routine, arg ) pthread_cleanup_push (routine, arg)
1012 * Unregisters the last cancellation handler.
1014 * This pops the cancellation handler that was last pushed with
1015 * vlc_cleanup_push() in the calling thread.
1017 # define vlc_cleanup_pop( ) pthread_cleanup_pop (0)
1019 #else /* !LIBVLC_USE_PTHREAD_CLEANUP */
1020 struct vlc_cleanup_t
1022 vlc_cleanup_t *next;
1023 void (*proc) (void *);
1024 void *data;
1027 # ifndef __cplusplus
1028 /* This macros opens a code block on purpose: It reduces the chance of
1029 * not pairing the push and pop. It also matches the POSIX Thread internals.
1030 * That way, Win32 developers will not accidentally break other platforms.
1032 # define vlc_cleanup_push( routine, arg ) \
1033 do { \
1034 vlc_control_cancel(&(vlc_cleanup_t){ NULL, routine, arg })
1036 # define vlc_cleanup_pop( ) \
1037 vlc_control_cancel (NULL); \
1038 } while (0)
1039 # else
1040 # define vlc_cleanup_push(routine, arg) \
1041 static_assert(false, "don't use vlc_cleanup_push in portable C++ code")
1042 # define vlc_cleanup_pop() \
1043 static_assert(false, "don't use vlc_cleanup_pop in portable C++ code")
1044 # endif
1046 #endif /* !LIBVLC_USE_PTHREAD_CLEANUP */
1048 static inline void vlc_cleanup_lock (void *lock)
1050 vlc_mutex_unlock ((vlc_mutex_t *)lock);
1052 #define mutex_cleanup_push( lock ) vlc_cleanup_push (vlc_cleanup_lock, lock)
1054 #ifndef __cplusplus
1055 void vlc_cancel_addr_set(atomic_uint *addr);
1056 void vlc_cancel_addr_clear(atomic_uint *addr);
1057 #else
1059 * Helper C++ class to lock a mutex.
1061 * The mutex is locked when the object is created, and unlocked when the object
1062 * is destroyed.
1064 class vlc_mutex_locker
1066 private:
1067 vlc_mutex_t *lock;
1068 public:
1069 vlc_mutex_locker (vlc_mutex_t *m) : lock (m)
1071 vlc_mutex_lock (lock);
1074 ~vlc_mutex_locker (void)
1076 vlc_mutex_unlock (lock);
1080 #endif
1082 enum
1084 VLC_AVCODEC_MUTEX = 0,
1085 VLC_GCRYPT_MUTEX,
1086 VLC_XLIB_MUTEX,
1087 VLC_MOSAIC_MUTEX,
1088 #ifdef _WIN32
1089 VLC_MTA_MUTEX,
1090 #endif
1091 /* Insert new entry HERE */
1092 VLC_MAX_MUTEX
1096 * Internal handler for global mutexes.
1098 * Do not use this function directly. Use helper macros instead:
1099 * vlc_global_lock(), vlc_global_unlock().
1101 VLC_API void vlc_global_mutex(unsigned, bool);
1104 * Acquires a global mutex.
1106 #define vlc_global_lock( n ) vlc_global_mutex(n, true)
1109 * Releases a global mutex.
1111 #define vlc_global_unlock( n ) vlc_global_mutex(n, false)
1113 /** @} */
1115 #endif /* !_VLC_THREADS_H */