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_
32 #include <stdatomic.h>
37 * \defgroup thread Threads and synchronization primitives
40 * Thread primitive declarations
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);
56 # define ETIMEDOUT 10060 /* This is the value in winsock.h. */
59 typedef struct vlc_thread
*vlc_thread_t
;
60 # define VLC_THREAD_CANCELED NULL
62 # define LIBVLC_NEED_SLEEP
63 #define LIBVLC_NEED_RWLOCK
64 typedef struct vlc_threadvar
*vlc_threadvar_t
;
65 typedef struct vlc_timer
*vlc_timer_t
;
67 # define VLC_THREAD_PRIORITY_LOW 0
68 # define VLC_THREAD_PRIORITY_INPUT THREAD_PRIORITY_ABOVE_NORMAL
69 # define VLC_THREAD_PRIORITY_AUDIO THREAD_PRIORITY_HIGHEST
70 # define VLC_THREAD_PRIORITY_VIDEO 0
71 # define VLC_THREAD_PRIORITY_OUTPUT THREAD_PRIORITY_ABOVE_NORMAL
72 # define VLC_THREAD_PRIORITY_HIGHEST THREAD_PRIORITY_TIME_CRITICAL
74 static inline int vlc_poll(struct pollfd
*fds
, unsigned nfds
, int timeout
)
79 val
= poll(fds
, nfds
, timeout
);
84 # define poll(u,n,t) vlc_poll(u, n, t)
86 #elif defined (__OS2__)
89 typedef struct vlc_thread
*vlc_thread_t
;
90 #define VLC_THREAD_CANCELED NULL
92 #define LIBVLC_NEED_RWLOCK
93 typedef struct vlc_threadvar
*vlc_threadvar_t
;
94 typedef struct vlc_timer
*vlc_timer_t
;
96 # define VLC_THREAD_PRIORITY_LOW 0
97 # define VLC_THREAD_PRIORITY_INPUT \
98 MAKESHORT(PRTYD_MAXIMUM / 2, PRTYC_REGULAR)
99 # define VLC_THREAD_PRIORITY_AUDIO MAKESHORT(PRTYD_MAXIMUM, PRTYC_REGULAR)
100 # define VLC_THREAD_PRIORITY_VIDEO 0
101 # define VLC_THREAD_PRIORITY_OUTPUT \
102 MAKESHORT(PRTYD_MAXIMUM / 2, PRTYC_REGULAR)
103 # define VLC_THREAD_PRIORITY_HIGHEST MAKESHORT(0, PRTYC_TIMECRITICAL)
105 # define pthread_sigmask sigprocmask
107 static inline int vlc_poll (struct pollfd
*fds
, unsigned nfds
, int timeout
)
109 static int (*vlc_poll_os2
)(struct pollfd
*, unsigned, int) = NULL
;
114 CHAR szFailed
[CCHMAXPATH
];
116 if (DosLoadModule(szFailed
, sizeof(szFailed
), "vlccore", &hmod
))
119 if (DosQueryProcAddr(hmod
, 0, "_vlc_poll_os2", (PFN
*)&vlc_poll_os2
))
123 return (*vlc_poll_os2
)(fds
, nfds
, timeout
);
125 # define poll(u,n,t) vlc_poll(u, n, t)
127 #elif defined (__ANDROID__) /* pthreads subset without pthread_cancel() */
129 # include <pthread.h>
131 # define LIBVLC_USE_PTHREAD_CLEANUP 1
132 # define LIBVLC_NEED_SLEEP
133 # define LIBVLC_NEED_RWLOCK
135 typedef struct vlc_thread
*vlc_thread_t
;
136 #define VLC_THREAD_CANCELED NULL
137 typedef pthread_key_t vlc_threadvar_t
;
138 typedef struct vlc_timer
*vlc_timer_t
;
140 # define VLC_THREAD_PRIORITY_LOW 0
141 # define VLC_THREAD_PRIORITY_INPUT 0
142 # define VLC_THREAD_PRIORITY_AUDIO 0
143 # define VLC_THREAD_PRIORITY_VIDEO 0
144 # define VLC_THREAD_PRIORITY_OUTPUT 0
145 # define VLC_THREAD_PRIORITY_HIGHEST 0
147 static inline int vlc_poll (struct pollfd
*fds
, unsigned nfds
, int timeout
)
153 int ugly_timeout
= ((unsigned)timeout
>= 50) ? 50 : timeout
;
155 timeout
-= ugly_timeout
;
158 val
= poll (fds
, nfds
, ugly_timeout
);
160 while (val
== 0 && timeout
!= 0);
165 # define poll(u,n,t) vlc_poll(u, n, t)
167 #else /* POSIX threads */
168 # include <unistd.h> /* _POSIX_SPIN_LOCKS */
169 # include <pthread.h>
172 * Whether LibVLC threads are based on POSIX threads.
174 # define LIBVLC_USE_PTHREAD 1
177 * Whether LibVLC thread cancellation is based on POSIX threads.
179 # define LIBVLC_USE_PTHREAD_CLEANUP 1
190 * Return value of a canceled thread.
192 #define VLC_THREAD_CANCELED PTHREAD_CANCELED
197 * Storage space for a slim reader/writer lock.
201 typedef pthread_rwlock_t vlc_rwlock_t
;
204 * Static initializer for (static) read/write lock.
208 #define VLC_STATIC_RWLOCK PTHREAD_RWLOCK_INITIALIZER
211 * Thread-local key handle.
215 typedef pthread_key_t vlc_threadvar_t
;
218 * Threaded timer handle.
222 typedef struct vlc_timer
*vlc_timer_t
;
224 /* Thread priorities.
225 * No effect for POSIX threads
227 # define VLC_THREAD_PRIORITY_LOW 0
228 # define VLC_THREAD_PRIORITY_INPUT 0
229 # define VLC_THREAD_PRIORITY_AUDIO 0
230 # define VLC_THREAD_PRIORITY_VIDEO 0
231 # define VLC_THREAD_PRIORITY_OUTPUT 0
232 # define VLC_THREAD_PRIORITY_HIGHEST 0
237 * \defgroup mutex Mutual exclusion locks
243 * Storage space for a mutual exclusion lock.
251 atomic_uint recursion
;
252 _Atomic (const void *) owner
;
257 unsigned int recursion
;
264 * Static initializer for (static) mutex.
266 * \note This only works in C code.
267 * In C++, consider using a global \ref vlc::threads::mutex instance instead.
269 #define VLC_STATIC_MUTEX { \
270 .value = ATOMIC_VAR_INIT(0), \
271 .recursion = ATOMIC_VAR_INIT(0), \
272 .owner = ATOMIC_VAR_INIT(NULL), \
276 * Initializes a fast mutex.
278 * Recursive locking of a fast mutex is undefined behaviour. (In debug builds,
279 * recursive locking will cause an assertion failure.)
281 VLC_API
void vlc_mutex_init(vlc_mutex_t
*);
284 * Initializes a recursive mutex.
285 * \warning This is strongly discouraged. Please use normal mutexes.
287 VLC_API
void vlc_mutex_init_recursive(vlc_mutex_t
*);
292 * If needed, this waits for any other thread to release it.
294 * \warning Beware of deadlocks when locking multiple mutexes at the same time,
295 * or when using mutexes from callbacks.
297 * \note This function is not a cancellation point.
299 VLC_API
void vlc_mutex_lock(vlc_mutex_t
*);
302 * Tries to acquire a mutex.
304 * This function acquires the mutex if and only if it is not currently held by
305 * another thread. This function never sleeps and can be used in delay-critical
308 * \note This function is not a cancellation point.
310 * \warning If this function fails, then the mutex is held... by another
311 * thread. The calling thread must deal with the error appropriately. That
312 * typically implies postponing the operations that would have required the
313 * mutex. If the thread cannot defer those operations, then it must use
314 * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
316 * @return 0 if the mutex could be acquired, an error code otherwise.
318 VLC_API
int vlc_mutex_trylock( vlc_mutex_t
* ) VLC_USED
;
323 * If the mutex is not held by the calling thread, the behaviour is undefined.
325 * \note This function is not a cancellation point.
327 VLC_API
void vlc_mutex_unlock(vlc_mutex_t
*);
330 * Checks if a mutex is locked.
332 * Do not use this function directly. Use vlc_mutex_assert() instead.
335 * This function has no effects.
336 * It is only meant to be use in run-time assertions.
338 * @warning This function might not return correct results in non-debug builds.
340 * @retval false the mutex is not locked by the calling thread
341 * @retval true the mutex is locked by the calling thread
343 VLC_API
bool vlc_mutex_held(const vlc_mutex_t
*) VLC_USED
;
346 * Asserts that a mutex is locked by the calling thread.
348 #define vlc_mutex_assert(m) assert(vlc_mutex_held(m))
353 * \defgroup condvar Condition variables
355 * The condition variable is the most common and generic mean for threads to
356 * wait for events triggered by other threads.
358 * See also POSIX @c pthread_cond_t .
362 struct vlc_cond_waiter
;
365 * Condition variable.
367 * Storage space for a thread condition variable.
371 struct vlc_cond_waiter
*head
;
376 * Static initializer for (static) condition variable.
378 #define VLC_STATIC_COND { NULL, VLC_STATIC_MUTEX }
381 * Initializes a condition variable.
383 VLC_API
void vlc_cond_init(vlc_cond_t
*);
386 * Wakes up one thread waiting on a condition variable.
388 * If any thread is currently waiting on the condition variable, at least one
389 * of those threads will be woken up. Otherwise, this function has no effects.
391 * \note This function is not a cancellation point.
393 VLC_API
void vlc_cond_signal(vlc_cond_t
*);
396 * Wakes up all threads waiting on a condition variable.
398 * \note This function is not a cancellation point.
400 VLC_API
void vlc_cond_broadcast(vlc_cond_t
*);
403 * Waits on a condition variable.
405 * The calling thread will be suspended until another thread calls
406 * vlc_cond_signal() or vlc_cond_broadcast() on the same condition variable,
407 * the thread is cancelled with vlc_cancel(), or the system causes a
408 * <em>spurious</em> unsolicited wake-up.
410 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
411 * a recursive mutex. Although it is possible to use the same mutex for
412 * multiple condition, it is not valid to use different mutexes for the same
413 * condition variable at the same time from different threads.
415 * The canonical way to use a condition variable to wait for event foobar is:
417 vlc_mutex_lock(&lock);
420 vlc_cond_wait(&wait, &lock);
422 // -- foobar is now true, do something about it here --
424 vlc_mutex_unlock(&lock);
427 * \param cond condition variable to wait on
428 * \param mutex mutex which is unlocked while waiting,
429 * then locked again when waking up.
431 VLC_API
void vlc_cond_wait(vlc_cond_t
*cond
, vlc_mutex_t
*mutex
);
434 * Waits on a condition variable up to a certain date.
436 * This works like vlc_cond_wait() but with an additional time-out.
437 * The time-out is expressed as an absolute timestamp using the same arbitrary
438 * time reference as the vlc_tick_now() and vlc_tick_wait() functions.
440 * \param cond condition variable to wait on
441 * \param mutex mutex which is unlocked while waiting,
442 * then locked again when waking up
443 * \param deadline <b>absolute</b> timeout
445 * \return 0 if the condition was signaled, an error code in case of timeout.
447 VLC_API
int vlc_cond_timedwait(vlc_cond_t
*cond
, vlc_mutex_t
*mutex
,
448 vlc_tick_t deadline
);
450 int vlc_cond_timedwait_daytime(vlc_cond_t
*, vlc_mutex_t
*, time_t);
455 * \defgroup semaphore Semaphores
457 * The semaphore is the simplest thread synchronization primitive, consisting
458 * of a simple counter.
460 * See also POSIX @c sem_t .
467 * Storage space for a thread-safe semaphore.
480 * Initializes a semaphore.
482 * @param count initial semaphore value (typically 0)
484 VLC_API
void vlc_sem_init(vlc_sem_t
*, unsigned count
);
487 * Increments the value of a semaphore.
489 * \note This function is not a cancellation point.
491 * \return 0 on success, EOVERFLOW in case of integer overflow.
493 VLC_API
int vlc_sem_post(vlc_sem_t
*);
496 * Waits on a semaphore.
498 * This function atomically waits for the semaphore to become non-zero then
499 * decrements it, and returns. If the semaphore is non-zero on entry, it is
500 * immediately decremented.
502 * \note This function may be a point of cancellation.
504 VLC_API
void vlc_sem_wait(vlc_sem_t
*);
507 * Tries to decrement a semaphore.
509 * This function decrements the semaphore if its value is not zero.
511 * \param sem semaphore to decrement
513 * \retval 0 the semaphore was decremented
514 * \retval EAGAIN the semaphore was zero and could not be decremented
516 VLC_API
int vlc_sem_trywait(vlc_sem_t
*sem
) VLC_USED
;
519 * Waits on a semaphore within a deadline.
521 * This function waits for the semaphore just like vlc_sem_wait(), but only
522 * up to a given deadline.
524 * \param sem semaphore to wait for
525 * \param deadline deadline to wait until
527 * \retval 0 the semaphore was decremented
528 * \retval ETIMEDOUT the deadline was reached
530 VLC_API
int vlc_sem_timedwait(vlc_sem_t
*sem
, vlc_tick_t deadline
) VLC_USED
;
535 * \defgroup rwlock Read/write locks
537 * Read/write locks are a type of thread synchronization primitive meant to
538 * protect access to data that is mostly read, and rarely written.
539 * As long as no threads tries to acquire the lock for "writing", any number of
540 * threads can acquire the lock for "reading".
542 * See also POSIX @c pthread_rwlock_t .
547 #ifdef LIBVLC_NEED_RWLOCK
548 typedef struct vlc_rwlock
554 # define VLC_STATIC_RWLOCK { VLC_STATIC_MUTEX, VLC_STATIC_COND, 0 }
558 * Initializes a read/write lock.
560 * After use, a read/write lock must be deinitialized with
561 * vlc_rwlock_destroy().
563 VLC_API
void vlc_rwlock_init(vlc_rwlock_t
*);
566 * Destroys an initialized unused read/write lock.
568 VLC_API
void vlc_rwlock_destroy(vlc_rwlock_t
*);
571 * Acquires a read/write lock for reading.
573 * \note Recursion is allowed.
575 VLC_API
void vlc_rwlock_rdlock(vlc_rwlock_t
*);
578 * Acquires a read/write lock for writing. Recursion is not allowed.
580 VLC_API
void vlc_rwlock_wrlock(vlc_rwlock_t
*);
583 * Releases a read/write lock.
585 * The calling thread must hold the lock. Otherwise behaviour is undefined.
587 * \note This function is not a cancellation point.
589 VLC_API
void vlc_rwlock_unlock(vlc_rwlock_t
*);
595 * One-time initialization.
597 * A one-time initialization object must always be initialized assigned to
598 * \ref VLC_STATIC_ONCE before use.
606 * Static initializer for one-time initialization.
608 #define VLC_STATIC_ONCE { ATOMIC_VAR_INIT(0) }
611 * Executes a function one time.
613 * The first time this function is called with a given one-time initialization
614 * object, it executes the provided callback.
615 * Any further call with the same object will be a no-op.
617 * In the corner case that the first time execution is ongoing in another
618 * thread, then the function will wait for completion on the other thread
619 * (and then synchronize memory) before it returns.
620 * This ensures that, no matter what, the callback has been executed exactly
621 * once and its side effects are visible after the function returns.
623 * \param once a one-time initialization object
624 * \param cb callback to execute (the first time)
626 VLC_API
void vlc_once(vlc_once_t
*restrict once
, void (*cb
)(void));
628 static inline void vlc_once_inline(vlc_once_t
*restrict once
, void (*cb
)(void))
630 /* Fast path: check if already initialized */
631 if (unlikely(atomic_load_explicit(&once
->value
, memory_order_acquire
) < 3))
634 #define vlc_once(once, cb) vlc_once_inline(once, cb)
638 * \defgroup threadvar Thread-specific variables
642 * Allocates a thread-specific variable.
644 * @param key where to store the thread-specific variable handle
645 * @param destr a destruction callback. It is called whenever a thread exits
646 * and the thread-specific variable has a non-NULL value.
648 * @return 0 on success, a system error code otherwise.
649 * This function can actually fail: on most systems, there is a fixed limit to
650 * the number of thread-specific variables in a given process.
652 VLC_API
int vlc_threadvar_create(vlc_threadvar_t
*key
, void (*destr
) (void *));
655 * Deallocates a thread-specific variable.
657 VLC_API
void vlc_threadvar_delete(vlc_threadvar_t
*);
660 * Sets a thread-specific variable.
662 * \param key thread-local variable key (created with vlc_threadvar_create())
663 * \param value new value for the variable for the calling thread
664 * \return 0 on success, a system error code otherwise.
666 VLC_API
int vlc_threadvar_set(vlc_threadvar_t key
, void *value
);
669 * Gets the value of a thread-local variable for the calling thread.
670 * This function cannot fail.
672 * \return the value associated with the given variable for the calling
673 * or NULL if no value was set.
675 VLC_API
void *vlc_threadvar_get(vlc_threadvar_t
);
680 * Waits on an address.
682 * Puts the calling thread to sleep if a specific unsigned 32-bits value is
683 * stored at a specified address. The thread will sleep until it is woken up by
684 * a call to vlc_atomic_notify_one() or vlc_atomic_notify_all() in another
685 * thread, or spuriously.
687 * If the value does not match, do nothing and return immediately.
689 * \param addr address to check for
690 * \param val value to match at the address
692 void vlc_atomic_wait(void *addr
, unsigned val
);
695 * Waits on an address with a time-out.
697 * This function operates as vlc_atomic_wait() but provides an additional
698 * time-out. If the deadline is reached, the thread resumes and the function
701 * \param addr address to check for
702 * \param val value to match at the address
703 * \param deadline deadline to wait until
705 * \retval 0 the function was woken up before the time-out
706 * \retval ETIMEDOUT the deadline was reached
708 int vlc_atomic_timedwait(void *addr
, unsigned val
, vlc_tick_t deadline
);
710 int vlc_atomic_timedwait_daytime(void *addr
, unsigned val
, time_t deadline
);
713 * Wakes up one thread on an address.
715 * Wakes up (at least) one of the thread sleeping on the specified address.
716 * The address must be equal to the first parameter given by at least one
717 * thread sleeping within the vlc_atomic_wait() or vlc_atomic_timedwait()
718 * functions. If no threads are found, this function does nothing.
720 * \param addr address identifying which threads may be woken up
722 void vlc_atomic_notify_one(void *addr
);
725 * Wakes up all thread on an address.
727 * Wakes up all threads sleeping on the specified address (if any).
728 * Any thread sleeping within a call to vlc_atomic_wait() or
729 * vlc_atomic_timedwait() with the specified address as first call parameter
732 * \param addr address identifying which threads to wake up
734 void vlc_atomic_notify_all(void *addr
);
737 * Creates and starts a new thread.
739 * The thread must be <i>joined</i> with vlc_join() to reclaim resources
740 * when it is not needed anymore.
742 * @param th storage space for the handle of the new thread (cannot be NULL)
744 * @param entry entry point for the thread
745 * @param data data parameter given to the entry point
746 * @param priority thread priority value
747 * @return 0 on success, a standard error code on error.
748 * @note In case of error, the value of *th is undefined.
750 VLC_API
int vlc_clone(vlc_thread_t
*th
, void *(*entry
)(void *), void *data
,
751 int priority
) VLC_USED
;
754 * Marks a thread as cancelled.
756 * Next time the target thread reaches a cancellation point (while not having
757 * disabled cancellation), it will run its cancellation cleanup handler, the
758 * thread variable destructors, and terminate.
760 * vlc_join() must be used regardless of a thread being cancelled or not, to
761 * avoid leaking resources.
763 VLC_API
void vlc_cancel(vlc_thread_t
);
766 * Waits for a thread to complete (if needed), then destroys it.
768 * \note This is a cancellation point. In case of cancellation, the thread is
771 * \warning A thread cannot join itself (normally VLC will abort if this is
772 * attempted). Also a detached thread <b>cannot</b> be joined.
774 * @param th thread handle
775 * @param result [OUT] pointer to write the thread return value or NULL
777 VLC_API
void vlc_join(vlc_thread_t th
, void **result
);
780 * Disables thread cancellation.
782 * This functions saves the current cancellation state (enabled or disabled),
783 * then disables cancellation for the calling thread. It must be called before
784 * entering a piece of code that is not cancellation-safe, unless it can be
785 * proven that the calling thread will not be cancelled.
787 * \note This function is not a cancellation point.
789 * \return Previous cancellation state (opaque value for vlc_restorecancel()).
791 VLC_API
int vlc_savecancel(void);
794 * Restores the cancellation state.
796 * This function restores the cancellation state of the calling thread to
797 * a state previously saved by vlc_savecancel().
799 * \note This function is not a cancellation point.
801 * \param state previous state as returned by vlc_savecancel().
803 VLC_API
void vlc_restorecancel(int state
);
805 typedef struct vlc_cleanup_t vlc_cleanup_t
;
808 * Internal handler for thread cancellation.
810 * Do not call this function directly. Use wrapper macros instead:
811 * vlc_cleanup_push(), vlc_cleanup_pop().
813 VLC_API
void vlc_control_cancel(vlc_cleanup_t
*);
818 * This function returns the identifier of the calling thread. The identifier
819 * cannot change for the entire duration of the thread, and no other thread can
820 * have the same identifier at the same time in the same process. Typically,
821 * the identifier is also unique across all running threads of all existing
822 * processes, but that depends on the operating system.
824 * There are no particular semantics to the thread ID with LibVLC.
825 * It is provided mainly for tracing and debugging.
827 * \warning This function is not currently implemented on all supported
828 * platforms. Where not implemented, it returns (unsigned long)-1.
830 * \return the thread identifier (or -1 if unimplemented)
832 VLC_API
unsigned long vlc_thread_id(void) VLC_USED
;
835 * Precision monotonic clock.
837 * In principles, the clock has a precision of 1 MHz. But the actual resolution
838 * may be much lower, especially when it comes to sleeping with vlc_tick_wait() or
839 * vlc_tick_sleep(). Most general-purpose operating systems provide a resolution of
840 * only 100 to 1000 Hz.
842 * \warning The origin date (time value "zero") is not specified. It is
843 * typically the time the kernel started, but this is platform-dependent.
844 * If you need wall clock time, use gettimeofday() instead.
846 * \return a timestamp in microseconds.
848 VLC_API vlc_tick_t
vlc_tick_now(void);
851 * Waits until a deadline.
853 * \param deadline timestamp to wait for (\ref vlc_tick_now())
855 * \note The deadline may be exceeded due to OS scheduling.
856 * \note This function is a cancellation point.
858 VLC_API
void vlc_tick_wait(vlc_tick_t deadline
);
861 * Waits for an interval of time.
863 * \param delay how long to wait (in microseconds)
865 * \note The delay may be exceeded due to OS scheduling.
866 * \note This function is a cancellation point.
868 VLC_API
void vlc_tick_sleep(vlc_tick_t delay
);
870 #define VLC_HARD_MIN_SLEEP VLC_TICK_FROM_MS(10) /* 10 milliseconds = 1 tick at 100Hz */
871 #define VLC_SOFT_MIN_SLEEP VLC_TICK_FROM_SEC(9) /* 9 seconds */
873 #if defined (__GNUC__) && !defined (__clang__)
874 /* Linux has 100, 250, 300 or 1000Hz
876 * HZ=100 by default on FreeBSD, but some architectures use a 1000Hz timer
880 __attribute__((unused
))
881 __attribute__((noinline
))
882 __attribute__((error("sorry, cannot sleep for such short a time")))
883 vlc_tick_t
impossible_delay( vlc_tick_t delay
)
886 return VLC_HARD_MIN_SLEEP
;
890 __attribute__((unused
))
891 __attribute__((noinline
))
892 __attribute__((warning("use proper event handling instead of short delay")))
893 vlc_tick_t
harmful_delay( vlc_tick_t delay
)
898 # define check_delay( d ) \
899 ((__builtin_constant_p(d < VLC_HARD_MIN_SLEEP) \
900 && (d < VLC_HARD_MIN_SLEEP)) \
901 ? impossible_delay(d) \
902 : ((__builtin_constant_p(d < VLC_SOFT_MIN_SLEEP) \
903 && (d < VLC_SOFT_MIN_SLEEP)) \
908 __attribute__((unused
))
909 __attribute__((noinline
))
910 __attribute__((error("deadlines can not be constant")))
911 vlc_tick_t
impossible_deadline( vlc_tick_t deadline
)
916 # define check_deadline( d ) \
917 (__builtin_constant_p(d) ? impossible_deadline(d) : d)
919 # define check_delay(d) (d)
920 # define check_deadline(d) (d)
923 #define vlc_tick_sleep(d) vlc_tick_sleep(check_delay(d))
924 #define vlc_tick_wait(d) vlc_tick_wait(check_deadline(d))
927 * \defgroup timer Asynchronous/threaded timers
931 * Initializes an asynchronous timer.
933 * \param id pointer to timer to be initialized
934 * \param func function that the timer will call
935 * \param data parameter for the timer function
936 * \return 0 on success, a system error code otherwise.
938 * \warning Asynchronous timers are processed from an unspecified thread.
939 * \note Multiple occurrences of a single interval timer are serialized:
940 * they cannot run concurrently.
942 VLC_API
int vlc_timer_create(vlc_timer_t
*id
, void (*func
)(void *), void *data
)
946 * Destroys an initialized timer.
948 * If needed, the timer is first disarmed. Behaviour is undefined if the
949 * specified timer is not initialized.
951 * \warning This function <b>must</b> be called before the timer data can be
952 * freed and before the timer callback function can be unmapped/unloaded.
954 * \param timer timer to destroy
956 VLC_API
void vlc_timer_destroy(vlc_timer_t timer
);
958 #define VLC_TIMER_DISARM (0)
959 #define VLC_TIMER_FIRE_ONCE (0)
962 * Arms or disarms an initialized timer.
964 * This functions overrides any previous call to itself.
966 * \note A timer can fire later than requested due to system scheduling
967 * limitations. An interval timer can fail to trigger sometimes, either because
968 * the system is busy or suspended, or because a previous iteration of the
969 * timer is still running. See also vlc_timer_getoverrun().
971 * \param timer initialized timer
972 * \param absolute the timer value origin is the same as vlc_tick_now() if true,
973 * the timer value is relative to now if false.
974 * \param value zero to disarm the timer, otherwise the initial time to wait
975 * before firing the timer.
976 * \param interval zero to fire the timer just once, otherwise the timer
977 * repetition interval.
979 VLC_API
void vlc_timer_schedule(vlc_timer_t timer
, bool absolute
,
980 vlc_tick_t value
, vlc_tick_t interval
);
982 static inline void vlc_timer_disarm(vlc_timer_t timer
)
984 vlc_timer_schedule( timer
, false, VLC_TIMER_DISARM
, 0 );
987 static inline void vlc_timer_schedule_asap(vlc_timer_t timer
, vlc_tick_t interval
)
989 vlc_timer_schedule(timer
, false, 1, interval
);
993 * Fetches and resets the overrun counter for a timer.
995 * This functions returns the number of times that the interval timer should
996 * have fired, but the callback was not invoked due to scheduling problems.
997 * The call resets the counter to zero.
999 * \param timer initialized timer
1000 * \return the timer overrun counter (typically zero)
1002 VLC_API
unsigned vlc_timer_getoverrun(vlc_timer_t
) VLC_USED
;
1009 * \return number of available (logical) CPUs.
1011 VLC_API
unsigned vlc_GetCPUCount(void);
1013 #if defined (LIBVLC_USE_PTHREAD_CLEANUP)
1015 * Registers a thread cancellation handler.
1017 * This pushes a function to run if the thread is cancelled (or otherwise
1018 * exits prematurely).
1020 * If multiple procedures are registered,
1021 * they are handled in last-in first-out order.
1023 * \note Any call to vlc_cleanup_push() <b>must</b> paired with a call to
1024 * vlc_cleanup_pop().
1025 * \warning Branching into or out of the block between these two function calls
1026 * is not allowed (read: it will likely crash the whole process).
1028 * \param routine procedure to call if the thread ends
1029 * \param arg argument for the procedure
1031 # define vlc_cleanup_push( routine, arg ) pthread_cleanup_push (routine, arg)
1034 * Unregisters the last cancellation handler.
1036 * This pops the cancellation handler that was last pushed with
1037 * vlc_cleanup_push() in the calling thread.
1039 # define vlc_cleanup_pop( ) pthread_cleanup_pop (0)
1041 #else /* !LIBVLC_USE_PTHREAD_CLEANUP */
1042 struct vlc_cleanup_t
1044 vlc_cleanup_t
*next
;
1045 void (*proc
) (void *);
1049 # ifndef __cplusplus
1050 /* This macros opens a code block on purpose: It reduces the chance of
1051 * not pairing the push and pop. It also matches the POSIX Thread internals.
1052 * That way, Win32 developers will not accidentally break other platforms.
1054 # define vlc_cleanup_push( routine, arg ) \
1056 vlc_control_cancel(&(vlc_cleanup_t){ NULL, routine, arg })
1058 # define vlc_cleanup_pop( ) \
1059 vlc_control_cancel (NULL); \
1062 # define vlc_cleanup_push(routine, arg) \
1063 static_assert(false, "don't use vlc_cleanup_push in portable C++ code")
1064 # define vlc_cleanup_pop() \
1065 static_assert(false, "don't use vlc_cleanup_pop in portable C++ code")
1068 #endif /* !LIBVLC_USE_PTHREAD_CLEANUP */
1070 static inline void vlc_cleanup_lock (void *lock
)
1072 vlc_mutex_unlock ((vlc_mutex_t
*)lock
);
1074 #define mutex_cleanup_push( lock ) vlc_cleanup_push (vlc_cleanup_lock, lock)
1077 void vlc_cancel_addr_set(atomic_uint
*addr
);
1078 void vlc_cancel_addr_clear(atomic_uint
*addr
);
1081 * Helper C++ class to lock a mutex.
1083 * The mutex is locked when the object is created, and unlocked when the object
1086 class vlc_mutex_locker
1091 vlc_mutex_locker (vlc_mutex_t
*m
) : lock (m
)
1093 vlc_mutex_lock (lock
);
1096 ~vlc_mutex_locker (void)
1098 vlc_mutex_unlock (lock
);
1106 VLC_AVCODEC_MUTEX
= 0,
1113 /* Insert new entry HERE */
1118 * Internal handler for global mutexes.
1120 * Do not use this function directly. Use helper macros instead:
1121 * vlc_global_lock(), vlc_global_unlock().
1123 VLC_API
void vlc_global_mutex(unsigned, bool);
1126 * Acquires a global mutex.
1128 #define vlc_global_lock( n ) vlc_global_mutex(n, true)
1131 * Releases a global mutex.
1133 #define vlc_global_unlock( n ) vlc_global_mutex(n, false)
1137 #endif /* !_VLC_THREADS_H */