opengl: implement subpictures renderer
[vlc.git] / include / vlc_threads.h
blob1b3cb278e4925ece84704c17cf062bfaa9b5ef0a
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 /**
32 * \ingroup os
33 * \defgroup thread Threads and synchronization primitives
34 * @{
35 * \file
36 * Thread primitive declarations
39 /**
40 * Issues an explicit deferred cancellation point.
42 * This has no effects if thread cancellation is disabled.
43 * This can be called when there is a rather slow non-sleeping operation.
44 * This is also used to force a cancellation point in a function that would
45 * otherwise <em>not always</em> be one (block_FifoGet() is an example).
47 VLC_API void vlc_testcancel(void);
49 #if defined (_WIN32)
50 # include <process.h>
51 # ifndef ETIMEDOUT
52 # define ETIMEDOUT 10060 /* This is the value in winsock.h. */
53 # endif
55 typedef struct vlc_thread *vlc_thread_t;
56 # define VLC_THREAD_CANCELED NULL
57 # define LIBVLC_NEED_SLEEP
58 typedef struct
60 bool dynamic;
61 union
63 struct
65 bool locked;
66 unsigned long contention;
68 CRITICAL_SECTION mutex;
70 } vlc_mutex_t;
71 #define VLC_STATIC_MUTEX { false, { { false, 0 } } }
72 #define LIBVLC_NEED_CONDVAR
73 #define LIBVLC_NEED_SEMAPHORE
74 #define LIBVLC_NEED_RWLOCK
75 typedef INIT_ONCE vlc_once_t;
76 #define VLC_STATIC_ONCE INIT_ONCE_STATIC_INIT
77 typedef struct vlc_threadvar *vlc_threadvar_t;
78 typedef struct vlc_timer *vlc_timer_t;
80 # define VLC_THREAD_PRIORITY_LOW 0
81 # define VLC_THREAD_PRIORITY_INPUT THREAD_PRIORITY_ABOVE_NORMAL
82 # define VLC_THREAD_PRIORITY_AUDIO THREAD_PRIORITY_HIGHEST
83 # define VLC_THREAD_PRIORITY_VIDEO 0
84 # define VLC_THREAD_PRIORITY_OUTPUT THREAD_PRIORITY_ABOVE_NORMAL
85 # define VLC_THREAD_PRIORITY_HIGHEST THREAD_PRIORITY_TIME_CRITICAL
87 static inline int vlc_poll(struct pollfd *fds, unsigned nfds, int timeout)
89 int val;
91 vlc_testcancel();
92 val = poll(fds, nfds, timeout);
93 if (val < 0)
94 vlc_testcancel();
95 return val;
97 # define poll(u,n,t) vlc_poll(u, n, t)
99 #elif defined (__OS2__)
100 # include <errno.h>
102 typedef struct vlc_thread *vlc_thread_t;
103 #define VLC_THREAD_CANCELED NULL
104 typedef struct
106 bool dynamic;
107 union
109 struct
111 bool locked;
112 unsigned long contention;
114 HMTX hmtx;
116 } vlc_mutex_t;
117 #define VLC_STATIC_MUTEX { false, { { false, 0 } } }
118 typedef struct
120 HEV hev;
121 unsigned waiters;
122 HEV hevAck;
123 unsigned signaled;
124 } vlc_cond_t;
125 #define VLC_STATIC_COND { NULLHANDLE, 0, NULLHANDLE, 0 }
126 #define LIBVLC_NEED_SEMAPHORE
127 #define LIBVLC_NEED_RWLOCK
128 typedef struct
130 unsigned done;
131 vlc_mutex_t mutex;
132 } vlc_once_t;
133 #define VLC_STATIC_ONCE { 0, VLC_STATIC_MUTEX }
134 typedef struct vlc_threadvar *vlc_threadvar_t;
135 typedef struct vlc_timer *vlc_timer_t;
137 # define VLC_THREAD_PRIORITY_LOW 0
138 # define VLC_THREAD_PRIORITY_INPUT \
139 MAKESHORT(PRTYD_MAXIMUM / 2, PRTYC_REGULAR)
140 # define VLC_THREAD_PRIORITY_AUDIO MAKESHORT(PRTYD_MAXIMUM, PRTYC_REGULAR)
141 # define VLC_THREAD_PRIORITY_VIDEO 0
142 # define VLC_THREAD_PRIORITY_OUTPUT \
143 MAKESHORT(PRTYD_MAXIMUM / 2, PRTYC_REGULAR)
144 # define VLC_THREAD_PRIORITY_HIGHEST MAKESHORT(0, PRTYC_TIMECRITICAL)
146 # define pthread_sigmask sigprocmask
148 static inline int vlc_poll (struct pollfd *fds, unsigned nfds, int timeout)
150 static int (*vlc_poll_os2)(struct pollfd *, unsigned, int) = NULL;
152 if (!vlc_poll_os2)
154 HMODULE hmod;
155 CHAR szFailed[CCHMAXPATH];
157 if (DosLoadModule(szFailed, sizeof(szFailed), "vlccore", &hmod))
158 return -1;
160 if (DosQueryProcAddr(hmod, 0, "_vlc_poll_os2", (PFN *)&vlc_poll_os2))
161 return -1;
164 return (*vlc_poll_os2)(fds, nfds, timeout);
166 # define poll(u,n,t) vlc_poll(u, n, t)
168 #elif defined (__ANDROID__) /* pthreads subset without pthread_cancel() */
169 # include <unistd.h>
170 # include <pthread.h>
171 # include <poll.h>
172 # define LIBVLC_USE_PTHREAD_CLEANUP 1
173 # define LIBVLC_NEED_SLEEP
174 # define LIBVLC_NEED_CONDVAR
175 # define LIBVLC_NEED_SEMAPHORE
176 # define LIBVLC_NEED_RWLOCK
178 typedef struct vlc_thread *vlc_thread_t;
179 #define VLC_THREAD_CANCELED NULL
180 typedef pthread_mutex_t vlc_mutex_t;
181 #define VLC_STATIC_MUTEX PTHREAD_MUTEX_INITIALIZER
182 typedef pthread_once_t vlc_once_t;
183 #define VLC_STATIC_ONCE PTHREAD_ONCE_INIT
184 typedef pthread_key_t vlc_threadvar_t;
185 typedef struct vlc_timer *vlc_timer_t;
187 # define VLC_THREAD_PRIORITY_LOW 0
188 # define VLC_THREAD_PRIORITY_INPUT 0
189 # define VLC_THREAD_PRIORITY_AUDIO 0
190 # define VLC_THREAD_PRIORITY_VIDEO 0
191 # define VLC_THREAD_PRIORITY_OUTPUT 0
192 # define VLC_THREAD_PRIORITY_HIGHEST 0
194 static inline int vlc_poll (struct pollfd *fds, unsigned nfds, int timeout)
196 int val;
200 int ugly_timeout = ((unsigned)timeout >= 50) ? 50 : timeout;
201 if (timeout >= 0)
202 timeout -= ugly_timeout;
204 vlc_testcancel ();
205 val = poll (fds, nfds, ugly_timeout);
207 while (val == 0 && timeout != 0);
209 return val;
212 # define poll(u,n,t) vlc_poll(u, n, t)
214 #elif defined (__APPLE__)
215 # define _APPLE_C_SOURCE 1 /* Proper pthread semantics on OSX */
216 # include <unistd.h>
217 # include <pthread.h>
218 /* Unnamed POSIX semaphores not supported on Mac OS X */
219 # include <mach/semaphore.h>
220 # include <mach/task.h>
221 # define LIBVLC_USE_PTHREAD_CLEANUP 1
223 typedef pthread_t vlc_thread_t;
224 #define VLC_THREAD_CANCELED PTHREAD_CANCELED
225 typedef pthread_mutex_t vlc_mutex_t;
226 #define VLC_STATIC_MUTEX PTHREAD_MUTEX_INITIALIZER
227 typedef pthread_cond_t vlc_cond_t;
228 #define VLC_STATIC_COND PTHREAD_COND_INITIALIZER
229 typedef semaphore_t vlc_sem_t;
230 typedef pthread_rwlock_t vlc_rwlock_t;
231 #define VLC_STATIC_RWLOCK PTHREAD_RWLOCK_INITIALIZER
232 typedef pthread_once_t vlc_once_t;
233 #define VLC_STATIC_ONCE PTHREAD_ONCE_INIT
234 typedef pthread_key_t vlc_threadvar_t;
235 typedef struct vlc_timer *vlc_timer_t;
237 # define VLC_THREAD_PRIORITY_LOW 0
238 # define VLC_THREAD_PRIORITY_INPUT 22
239 # define VLC_THREAD_PRIORITY_AUDIO 22
240 # define VLC_THREAD_PRIORITY_VIDEO 0
241 # define VLC_THREAD_PRIORITY_OUTPUT 22
242 # define VLC_THREAD_PRIORITY_HIGHEST 22
244 #else /* POSIX threads */
245 # include <unistd.h> /* _POSIX_SPIN_LOCKS */
246 # include <pthread.h>
247 # include <semaphore.h>
250 * Whether LibVLC threads are based on POSIX threads.
252 # define LIBVLC_USE_PTHREAD 1
255 * Whether LibVLC thread cancellation is based on POSIX threads.
257 # define LIBVLC_USE_PTHREAD_CLEANUP 1
260 * Thread handle.
262 typedef struct
264 pthread_t handle;
265 } vlc_thread_t;
268 * Return value of a canceled thread.
270 #define VLC_THREAD_CANCELED PTHREAD_CANCELED
273 * Mutex.
275 * Storage space for a mutual exclusion lock.
277 typedef pthread_mutex_t vlc_mutex_t;
280 * Static initializer for (static) mutex.
282 #define VLC_STATIC_MUTEX PTHREAD_MUTEX_INITIALIZER
285 * Condition variable.
287 * Storage space for a thread condition variable.
289 typedef pthread_cond_t vlc_cond_t;
292 * Static initializer for (static) condition variable.
294 * \note
295 * The condition variable will use the default clock, which is OS-dependent.
296 * Therefore, where timed waits are necessary the condition variable should
297 * always be initialized dynamically explicit instead of using this
298 * initializer.
300 #define VLC_STATIC_COND PTHREAD_COND_INITIALIZER
303 * Semaphore.
305 * Storage space for a thread-safe semaphore.
307 typedef sem_t vlc_sem_t;
310 * Read/write lock.
312 * Storage space for a slim reader/writer lock.
314 typedef pthread_rwlock_t vlc_rwlock_t;
317 * Static initializer for (static) read/write lock.
319 #define VLC_STATIC_RWLOCK PTHREAD_RWLOCK_INITIALIZER
322 * One-time initialization.
324 * A one-time initialization object must always be initialized assigned to
325 * \ref VLC_STATIC_ONCE before use.
327 typedef pthread_once_t vlc_once_t;
330 * Static initializer for one-time initialization.
332 #define VLC_STATIC_ONCE PTHREAD_ONCE_INIT
335 * Thread-local key handle.
337 typedef pthread_key_t vlc_threadvar_t;
340 * Threaded timer handle.
342 typedef struct vlc_timer *vlc_timer_t;
344 # define VLC_THREAD_PRIORITY_LOW 0
345 # define VLC_THREAD_PRIORITY_INPUT 10
346 # define VLC_THREAD_PRIORITY_AUDIO 5
347 # define VLC_THREAD_PRIORITY_VIDEO 0
348 # define VLC_THREAD_PRIORITY_OUTPUT 15
349 # define VLC_THREAD_PRIORITY_HIGHEST 20
351 #endif
353 #ifdef LIBVLC_NEED_CONDVAR
354 #ifndef __cplusplus
355 #include <stdatomic.h>
356 #endif
358 typedef struct
360 union {
361 #ifndef __cplusplus
362 atomic_uint value;
363 #endif
364 int cpp_value;
366 } vlc_cond_t;
367 # define VLC_STATIC_COND { 0 }
368 #endif
370 #ifdef LIBVLC_NEED_SEMAPHORE
371 typedef struct vlc_sem
373 vlc_mutex_t lock;
374 vlc_cond_t wait;
375 unsigned value;
376 } vlc_sem_t;
377 #endif
379 #ifdef LIBVLC_NEED_RWLOCK
380 typedef struct vlc_rwlock
382 vlc_mutex_t mutex;
383 vlc_cond_t wait;
384 long state;
385 } vlc_rwlock_t;
386 # define VLC_STATIC_RWLOCK { VLC_STATIC_MUTEX, VLC_STATIC_COND, 0 }
387 #endif
390 * Initializes a fast mutex.
392 * Recursive locking of a fast mutex is undefined behaviour. (In debug builds,
393 * recursive locking will cause an assertion failure.)
395 VLC_API void vlc_mutex_init(vlc_mutex_t *);
398 * Initializes a recursive mutex.
399 * \warning This is strongly discouraged. Please use normal mutexes.
401 VLC_API void vlc_mutex_init_recursive(vlc_mutex_t *);
404 * Deinitializes a mutex.
406 * The mutex must not be locked, otherwise behaviour is undefined.
408 VLC_API void vlc_mutex_destroy(vlc_mutex_t *);
411 * Acquires a mutex.
413 * If needed, this waits for any other thread to release it.
415 * \warning Beware of deadlocks when locking multiple mutexes at the same time,
416 * or when using mutexes from callbacks.
418 * \note This function is not a cancellation point.
420 VLC_API void vlc_mutex_lock(vlc_mutex_t *);
423 * Tries to acquire a mutex.
425 * This function acquires the mutex if and only if it is not currently held by
426 * another thread. This function never sleeps and can be used in delay-critical
427 * code paths.
429 * \note This function is not a cancellation point.
431 * \warning If this function fails, then the mutex is held... by another
432 * thread. The calling thread must deal with the error appropriately. That
433 * typically implies postponing the operations that would have required the
434 * mutex. If the thread cannot defer those operations, then it must use
435 * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
437 * @return 0 if the mutex could be acquired, an error code otherwise.
439 VLC_API int vlc_mutex_trylock( vlc_mutex_t * ) VLC_USED;
442 * Releases a mutex.
444 * If the mutex is not held by the calling thread, the behaviour is undefined.
446 * \note This function is not a cancellation point.
448 VLC_API void vlc_mutex_unlock(vlc_mutex_t *);
451 * Checks if a mutex is locked.
453 * Do not use this function directly. Use vlc_mutex_assert() instead.
455 * @note
456 * This function has no effects.
457 * It is only meant to be use in run-time assertions.
459 * @retval false in debug builds of LibVLC,
460 * if the mutex is not locked by the calling thread;
461 * @retval true in debug builds of LibVLC,
462 * if the mutex is locked by the calling thread;
463 * @retval true in release builds of LibVLC.
465 VLC_API bool vlc_mutex_marked(const vlc_mutex_t *) VLC_USED;
468 * Asserts that a mutex is locked by the calling thread.
470 #define vlc_mutex_assert(m) assert(vlc_mutex_marked(m))
473 * Initializes a condition variable.
475 VLC_API void vlc_cond_init(vlc_cond_t *);
478 * Initializes a condition variable (wall clock).
480 * This function initializes a condition variable for timed waiting using the
481 * UTC wall clock time. The time reference is the same as with time() and with
482 * timespec_get() and TIME_UTC.
483 * vlc_cond_timedwait_daytime() must be instead of
484 * vlc_cond_timedwait() for actual waiting.
486 void vlc_cond_init_daytime(vlc_cond_t *);
489 * Deinitializes a condition variable.
491 * No threads shall be waiting or signaling the condition, otherwise the
492 * behavior is undefined.
494 VLC_API void vlc_cond_destroy(vlc_cond_t *);
497 * Wakes up one thread waiting on a condition variable.
499 * If any thread is currently waiting on the condition variable, at least one
500 * of those threads will be woken up. Otherwise, this function has no effects.
502 * \note This function is not a cancellation point.
504 VLC_API void vlc_cond_signal(vlc_cond_t *);
507 * Wakes up all threads waiting on a condition variable.
509 * \note This function is not a cancellation point.
511 VLC_API void vlc_cond_broadcast(vlc_cond_t *);
514 * Waits on a condition variable.
516 * The calling thread will be suspended until another thread calls
517 * vlc_cond_signal() or vlc_cond_broadcast() on the same condition variable,
518 * the thread is cancelled with vlc_cancel(), or the system causes a
519 * <em>spurious</em> unsolicited wake-up.
521 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
522 * a recursive mutex. Although it is possible to use the same mutex for
523 * multiple condition, it is not valid to use different mutexes for the same
524 * condition variable at the same time from different threads.
526 * The canonical way to use a condition variable to wait for event foobar is:
527 @code
528 vlc_mutex_lock(&lock);
529 mutex_cleanup_push(&lock); // release the mutex in case of cancellation
531 while (!foobar)
532 vlc_cond_wait(&wait, &lock);
534 // -- foobar is now true, do something about it here --
536 vlc_cleanup_pop();
537 vlc_mutex_unlock(&lock);
538 @endcode
540 * \note This function is a cancellation point. In case of thread cancellation,
541 * the mutex is always locked before cancellation proceeds.
543 * \param cond condition variable to wait on
544 * \param mutex mutex which is unlocked while waiting,
545 * then locked again when waking up.
547 VLC_API void vlc_cond_wait(vlc_cond_t *cond, vlc_mutex_t *mutex);
550 * Waits on a condition variable up to a certain date.
552 * This works like vlc_cond_wait() but with an additional time-out.
553 * The time-out is expressed as an absolute timestamp using the same arbitrary
554 * time reference as the vlc_tick_now() and vlc_tick_wait() functions.
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
562 * \param deadline <b>absolute</b> timeout
564 * \warning If the variable was initialized with vlc_cond_init_daytime(), or
565 * was statically initialized with \ref VLC_STATIC_COND, the time reference
566 * used by this function is unspecified (depending on the implementation, it
567 * might be the Unix epoch or the vlc_tick_now() clock).
569 * \return 0 if the condition was signaled, an error code in case of timeout.
571 VLC_API int vlc_cond_timedwait(vlc_cond_t *cond, vlc_mutex_t *mutex,
572 vlc_tick_t deadline);
574 int vlc_cond_timedwait_daytime(vlc_cond_t *, vlc_mutex_t *, time_t);
577 * Initializes a semaphore.
579 * @param count initial semaphore value (typically 0)
581 VLC_API void vlc_sem_init(vlc_sem_t *, unsigned count);
584 * Deinitializes a semaphore.
586 VLC_API void vlc_sem_destroy(vlc_sem_t *);
589 * Increments the value of a semaphore.
591 * \note This function is not a cancellation point.
593 * \return 0 on success, EOVERFLOW in case of integer overflow.
595 VLC_API int vlc_sem_post(vlc_sem_t *);
598 * Waits on a semaphore.
600 * This function atomically waits for the semaphore to become non-zero then
601 * decrements it, and returns. If the semaphore is non-zero on entry, it is
602 * immediately decremented.
604 * \note This function may be a point of cancellation.
606 VLC_API void vlc_sem_wait(vlc_sem_t *);
609 * Initializes a read/write lock.
611 VLC_API void vlc_rwlock_init(vlc_rwlock_t *);
614 * Destroys an initialized unused read/write lock.
616 VLC_API void vlc_rwlock_destroy(vlc_rwlock_t *);
619 * Acquires a read/write lock for reading.
621 * \note Recursion is allowed.
622 * \note This function may be a point of cancellation.
624 VLC_API void vlc_rwlock_rdlock(vlc_rwlock_t *);
627 * Acquires a read/write lock for writing. Recursion is not allowed.
628 * \note This function may be a point of cancellation.
630 VLC_API void vlc_rwlock_wrlock(vlc_rwlock_t *);
633 * Releases a read/write lock.
635 * The calling thread must hold the lock. Otherwise behaviour is undefined.
637 * \note This function is not a cancellation point.
639 VLC_API void vlc_rwlock_unlock(vlc_rwlock_t *);
642 * Executes a function one time.
644 * The first time this function is called with a given one-time initialization
645 * object, it executes the provided callback.
646 * Any further call with the same object will be a no-op.
648 * In the corner case that the first time execution is ongoing in another
649 * thread, then the function will wait for completion on the other thread
650 * (and then synchronize memory) before it returns.
651 * This ensures that, no matter what, the callback has been executed exactly
652 * once and its side effects are visible after the function returns.
654 * \param once a one-time initialization object
655 * \param cb callback to execute (the first time)
657 VLC_API void vlc_once(vlc_once_t *restrict once, void (*cb)(void));
660 * Allocates a thread-specific variable.
662 * @param key where to store the thread-specific variable handle
663 * @param destr a destruction callback. It is called whenever a thread exits
664 * and the thread-specific variable has a non-NULL value.
666 * @return 0 on success, a system error code otherwise.
667 * This function can actually fail: on most systems, there is a fixed limit to
668 * the number of thread-specific variables in a given process.
670 VLC_API int vlc_threadvar_create(vlc_threadvar_t *key, void (*destr) (void *));
673 * Deallocates a thread-specific variable.
675 VLC_API void vlc_threadvar_delete(vlc_threadvar_t *);
678 * Sets a thread-specific variable.
680 * \param key thread-local variable key (created with vlc_threadvar_create())
681 * \param value new value for the variable for the calling thread
682 * \return 0 on success, a system error code otherwise.
684 VLC_API int vlc_threadvar_set(vlc_threadvar_t key, void *value);
687 * Gets the value of a thread-local variable for the calling thread.
688 * This function cannot fail.
690 * \return the value associated with the given variable for the calling
691 * or NULL if no value was set.
693 VLC_API void *vlc_threadvar_get(vlc_threadvar_t);
696 * Waits on an address.
698 * Puts the calling thread to sleep if a specific unsigned 32-bits value is
699 * stored at a specified address. The thread will sleep until it is woken up by
700 * a call to vlc_atomic_notify_one() or vlc_atomic_notify_all() in another
701 * thread, or spuriously.
703 * If the value does not match, do nothing and return immediately.
705 * \param addr address to check for
706 * \param val value to match at the address
708 void vlc_atomic_wait(void *addr, unsigned val);
711 * Waits on an address with a time-out.
713 * This function operates as vlc_atomic_wait() but provides an additional
714 * time-out. If the time-out elapses, the thread resumes and the function
715 * returns.
717 * \param addr address to check for
718 * \param val value to match at the address
719 * \param delay time-out duration
721 * \retval true the function was woken up before the time-out
722 * \retval false the time-out elapsed
724 bool vlc_atomic_timedwait(void *addr, unsigned val, vlc_tick_t delay);
727 * Wakes up one thread on an address.
729 * Wakes up (at least) one of the thread sleeping on the specified address.
730 * The address must be equal to the first parameter given by at least one
731 * thread sleeping within the vlc_atomic_wait() or vlc_atomic_timedwait()
732 * functions. If no threads are found, this function does nothing.
734 * \param addr address identifying which threads may be woken up
736 void vlc_atomic_notify_one(void *addr);
739 * Wakes up all thread on an address.
741 * Wakes up all threads sleeping on the specified address (if any).
742 * Any thread sleeping within a call to vlc_atomic_wait() or
743 * vlc_atomic_timedwait() with the specified address as first call parameter
744 * will be woken up.
746 * \param addr address identifying which threads to wake up
748 void vlc_atomic_notify_all(void *addr);
751 * Creates and starts a new thread.
753 * The thread must be <i>joined</i> with vlc_join() to reclaim resources
754 * when it is not needed anymore.
756 * @param th storage space for the handle of the new thread (cannot be NULL)
757 * [OUT]
758 * @param entry entry point for the thread
759 * @param data data parameter given to the entry point
760 * @param priority thread priority value
761 * @return 0 on success, a standard error code on error.
762 * @note In case of error, the value of *th is undefined.
764 VLC_API int vlc_clone(vlc_thread_t *th, void *(*entry)(void *), void *data,
765 int priority) VLC_USED;
768 * Marks a thread as cancelled.
770 * Next time the target thread reaches a cancellation point (while not having
771 * disabled cancellation), it will run its cancellation cleanup handler, the
772 * thread variable destructors, and terminate.
774 * vlc_join() must be used regardless of a thread being cancelled or not, to
775 * avoid leaking resources.
777 VLC_API void vlc_cancel(vlc_thread_t);
780 * Waits for a thread to complete (if needed), then destroys it.
782 * \note This is a cancellation point. In case of cancellation, the thread is
783 * <b>not</b> joined.
785 * \warning A thread cannot join itself (normally VLC will abort if this is
786 * attempted). Also a detached thread <b>cannot</b> be joined.
788 * @param th thread handle
789 * @param result [OUT] pointer to write the thread return value or NULL
791 VLC_API void vlc_join(vlc_thread_t th, void **result);
794 * Disables thread cancellation.
796 * This functions saves the current cancellation state (enabled or disabled),
797 * then disables cancellation for the calling thread. It must be called before
798 * entering a piece of code that is not cancellation-safe, unless it can be
799 * proven that the calling thread will not be cancelled.
801 * \note This function is not a cancellation point.
803 * \return Previous cancellation state (opaque value for vlc_restorecancel()).
805 VLC_API int vlc_savecancel(void);
808 * Restores the cancellation state.
810 * This function restores the cancellation state of the calling thread to
811 * a state previously saved by vlc_savecancel().
813 * \note This function is not a cancellation point.
815 * \param state previous state as returned by vlc_savecancel().
817 VLC_API void vlc_restorecancel(int state);
819 typedef struct vlc_cleanup_t vlc_cleanup_t;
822 * Internal handler for thread cancellation.
824 * Do not call this function directly. Use wrapper macros instead:
825 * vlc_cleanup_push(), vlc_cleanup_pop().
827 VLC_API void vlc_control_cancel(vlc_cleanup_t *);
830 * Thread handle.
832 * This function returns the thread handle of the calling thread.
834 * \note The exact type of the thread handle depends on the platform,
835 * including an integer type, a pointer type or a compound type of any size.
836 * If you need an integer identifier, use vlc_thread_id() instead.
838 * \note vlc_join(vlc_thread_self(), NULL) is undefined,
839 * as it obviously does not make any sense (it might result in a deadlock, but
840 * there are no warranties that it will).
842 * \return the thread handle
844 VLC_API vlc_thread_t vlc_thread_self(void) VLC_USED;
847 * Thread identifier.
849 * This function returns the identifier of the calling thread. The identifier
850 * cannot change for the entire duration of the thread, and no other thread can
851 * have the same identifier at the same time in the same process. Typically,
852 * the identifier is also unique across all running threads of all existing
853 * processes, but that depends on the operating system.
855 * There are no particular semantics to the thread ID with LibVLC.
856 * It is provided mainly for tracing and debugging.
858 * \warning This function is not currently implemented on all supported
859 * platforms. Where not implemented, it returns (unsigned long)-1.
861 * \return the thread identifier (or -1 if unimplemented)
863 VLC_API unsigned long vlc_thread_id(void) VLC_USED;
866 * Precision monotonic clock.
868 * In principles, the clock has a precision of 1 MHz. But the actual resolution
869 * may be much lower, especially when it comes to sleeping with vlc_tick_wait() or
870 * vlc_tick_sleep(). Most general-purpose operating systems provide a resolution of
871 * only 100 to 1000 Hz.
873 * \warning The origin date (time value "zero") is not specified. It is
874 * typically the time the kernel started, but this is platform-dependent.
875 * If you need wall clock time, use gettimeofday() instead.
877 * \return a timestamp in microseconds.
879 VLC_API vlc_tick_t vlc_tick_now(void);
882 * Waits until a deadline.
884 * \param deadline timestamp to wait for (\ref vlc_tick_now())
886 * \note The deadline may be exceeded due to OS scheduling.
887 * \note This function is a cancellation point.
889 VLC_API void vlc_tick_wait(vlc_tick_t deadline);
892 * Waits for an interval of time.
894 * \param delay how long to wait (in microseconds)
896 * \note The delay may be exceeded due to OS scheduling.
897 * \note This function is a cancellation point.
899 VLC_API void vlc_tick_sleep(vlc_tick_t delay);
901 #define VLC_HARD_MIN_SLEEP VLC_TICK_FROM_MS(10) /* 10 milliseconds = 1 tick at 100Hz */
902 #define VLC_SOFT_MIN_SLEEP VLC_TICK_FROM_SEC(9) /* 9 seconds */
904 #if defined (__GNUC__) && !defined (__clang__)
905 /* Linux has 100, 250, 300 or 1000Hz
907 * HZ=100 by default on FreeBSD, but some architectures use a 1000Hz timer
910 static
911 __attribute__((unused))
912 __attribute__((noinline))
913 __attribute__((error("sorry, cannot sleep for such short a time")))
914 vlc_tick_t impossible_delay( vlc_tick_t delay )
916 (void) delay;
917 return VLC_HARD_MIN_SLEEP;
920 static
921 __attribute__((unused))
922 __attribute__((noinline))
923 __attribute__((warning("use proper event handling instead of short delay")))
924 vlc_tick_t harmful_delay( vlc_tick_t delay )
926 return delay;
929 # define check_delay( d ) \
930 ((__builtin_constant_p(d < VLC_HARD_MIN_SLEEP) \
931 && (d < VLC_HARD_MIN_SLEEP)) \
932 ? impossible_delay(d) \
933 : ((__builtin_constant_p(d < VLC_SOFT_MIN_SLEEP) \
934 && (d < VLC_SOFT_MIN_SLEEP)) \
935 ? harmful_delay(d) \
936 : d))
938 static
939 __attribute__((unused))
940 __attribute__((noinline))
941 __attribute__((error("deadlines can not be constant")))
942 vlc_tick_t impossible_deadline( vlc_tick_t deadline )
944 return deadline;
947 # define check_deadline( d ) \
948 (__builtin_constant_p(d) ? impossible_deadline(d) : d)
949 #else
950 # define check_delay(d) (d)
951 # define check_deadline(d) (d)
952 #endif
954 #define vlc_tick_sleep(d) vlc_tick_sleep(check_delay(d))
955 #define vlc_tick_wait(d) vlc_tick_wait(check_deadline(d))
958 * Initializes an asynchronous timer.
960 * \param id pointer to timer to be initialized
961 * \param func function that the timer will call
962 * \param data parameter for the timer function
963 * \return 0 on success, a system error code otherwise.
965 * \warning Asynchronous timers are processed from an unspecified thread.
966 * \note Multiple occurrences of a single interval timer are serialized:
967 * they cannot run concurrently.
969 VLC_API int vlc_timer_create(vlc_timer_t *id, void (*func)(void *), void *data)
970 VLC_USED;
973 * Destroys an initialized timer.
975 * If needed, the timer is first disarmed. Behaviour is undefined if the
976 * specified timer is not initialized.
978 * \warning This function <b>must</b> be called before the timer data can be
979 * freed and before the timer callback function can be unmapped/unloaded.
981 * \param timer timer to destroy
983 VLC_API void vlc_timer_destroy(vlc_timer_t timer);
985 #define VLC_TIMER_DISARM (0)
986 #define VLC_TIMER_FIRE_ONCE (0)
989 * Arms or disarms an initialized timer.
991 * This functions overrides any previous call to itself.
993 * \note A timer can fire later than requested due to system scheduling
994 * limitations. An interval timer can fail to trigger sometimes, either because
995 * the system is busy or suspended, or because a previous iteration of the
996 * timer is still running. See also vlc_timer_getoverrun().
998 * \param timer initialized timer
999 * \param absolute the timer value origin is the same as vlc_tick_now() if true,
1000 * the timer value is relative to now if false.
1001 * \param value zero to disarm the timer, otherwise the initial time to wait
1002 * before firing the timer.
1003 * \param interval zero to fire the timer just once, otherwise the timer
1004 * repetition interval.
1006 VLC_API void vlc_timer_schedule(vlc_timer_t timer, bool absolute,
1007 vlc_tick_t value, vlc_tick_t interval);
1009 static inline void vlc_timer_disarm(vlc_timer_t timer)
1011 vlc_timer_schedule( timer, false, VLC_TIMER_DISARM, 0 );
1014 static inline void vlc_timer_schedule_asap(vlc_timer_t timer, vlc_tick_t interval)
1016 vlc_timer_schedule(timer, false, 1, interval);
1020 * Fetches and resets the overrun counter for a timer.
1022 * This functions returns the number of times that the interval timer should
1023 * have fired, but the callback was not invoked due to scheduling problems.
1024 * The call resets the counter to zero.
1026 * \param timer initialized timer
1027 * \return the timer overrun counter (typically zero)
1029 VLC_API unsigned vlc_timer_getoverrun(vlc_timer_t) VLC_USED;
1032 * Count CPUs.
1034 * \return number of available (logical) CPUs.
1036 VLC_API unsigned vlc_GetCPUCount(void);
1038 #if defined (LIBVLC_USE_PTHREAD_CLEANUP)
1040 * Registers a thread cancellation handler.
1042 * This pushes a function to run if the thread is cancelled (or otherwise
1043 * exits prematurely).
1045 * If multiple procedures are registered,
1046 * they are handled in last-in first-out order.
1048 * \note Any call to vlc_cleanup_push() <b>must</b> paired with a call to
1049 * vlc_cleanup_pop().
1050 * \warning Branching into or out of the block between these two function calls
1051 * is not allowed (read: it will likely crash the whole process).
1053 * \param routine procedure to call if the thread ends
1054 * \param arg argument for the procedure
1056 # define vlc_cleanup_push( routine, arg ) pthread_cleanup_push (routine, arg)
1059 * Unregisters the last cancellation handler.
1061 * This pops the cancellation handler that was last pushed with
1062 * vlc_cleanup_push() in the calling thread.
1064 # define vlc_cleanup_pop( ) pthread_cleanup_pop (0)
1066 #else /* !LIBVLC_USE_PTHREAD_CLEANUP */
1067 struct vlc_cleanup_t
1069 vlc_cleanup_t *next;
1070 void (*proc) (void *);
1071 void *data;
1074 # ifndef __cplusplus
1075 /* This macros opens a code block on purpose: It reduces the chance of
1076 * not pairing the push and pop. It also matches the POSIX Thread internals.
1077 * That way, Win32 developers will not accidentally break other platforms.
1079 # define vlc_cleanup_push( routine, arg ) \
1080 do { \
1081 vlc_control_cancel(&(vlc_cleanup_t){ NULL, routine, arg })
1083 # define vlc_cleanup_pop( ) \
1084 vlc_control_cancel (NULL); \
1085 } while (0)
1086 # else
1087 # define vlc_cleanup_push(routine, arg) \
1088 static_assert(false, "don't use vlc_cleanup_push in portable C++ code")
1089 # define vlc_cleanup_pop() \
1090 static_assert(false, "don't use vlc_cleanup_pop in portable C++ code")
1091 # endif
1093 #endif /* !LIBVLC_USE_PTHREAD_CLEANUP */
1095 static inline void vlc_cleanup_lock (void *lock)
1097 vlc_mutex_unlock ((vlc_mutex_t *)lock);
1099 #define mutex_cleanup_push( lock ) vlc_cleanup_push (vlc_cleanup_lock, lock)
1101 #if defined(LIBVLC_NEED_CONDVAR) && !defined(__cplusplus)
1102 void vlc_cancel_addr_set(atomic_uint *addr);
1103 void vlc_cancel_addr_clear(atomic_uint *addr);
1104 #endif
1106 #ifdef __cplusplus
1108 * Helper C++ class to lock a mutex.
1110 * The mutex is locked when the object is created, and unlocked when the object
1111 * is destroyed.
1113 class vlc_mutex_locker
1115 private:
1116 vlc_mutex_t *lock;
1117 public:
1118 vlc_mutex_locker (vlc_mutex_t *m) : lock (m)
1120 vlc_mutex_lock (lock);
1123 ~vlc_mutex_locker (void)
1125 vlc_mutex_unlock (lock);
1129 #endif
1131 enum
1133 VLC_AVCODEC_MUTEX = 0,
1134 VLC_GCRYPT_MUTEX,
1135 VLC_XLIB_MUTEX,
1136 VLC_MOSAIC_MUTEX,
1137 #ifdef _WIN32
1138 VLC_MTA_MUTEX,
1139 #endif
1140 /* Insert new entry HERE */
1141 VLC_MAX_MUTEX
1145 * Internal handler for global mutexes.
1147 * Do not use this function directly. Use helper macros instead:
1148 * vlc_global_lock(), vlc_global_unlock().
1150 VLC_API void vlc_global_mutex(unsigned, bool);
1153 * Acquires a global mutex.
1155 #define vlc_global_lock( n ) vlc_global_mutex(n, true)
1158 * Releases a global mutex.
1160 #define vlc_global_unlock( n ) vlc_global_mutex(n, false)
1162 /** @} */
1164 #endif /* !_VLC_THREADS_H */