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 typedef unsigned long vlc_osthread_t
;
63 #define vlc_thread_equal(a,b) ((a) == (b))
65 # define LIBVLC_NEED_SLEEP
66 #define LIBVLC_NEED_RWLOCK
67 typedef INIT_ONCE vlc_once_t
;
68 #define VLC_STATIC_ONCE INIT_ONCE_STATIC_INIT
69 typedef struct vlc_threadvar
*vlc_threadvar_t
;
70 typedef struct vlc_timer
*vlc_timer_t
;
72 # define VLC_THREAD_PRIORITY_LOW 0
73 # define VLC_THREAD_PRIORITY_INPUT THREAD_PRIORITY_ABOVE_NORMAL
74 # define VLC_THREAD_PRIORITY_AUDIO THREAD_PRIORITY_HIGHEST
75 # define VLC_THREAD_PRIORITY_VIDEO 0
76 # define VLC_THREAD_PRIORITY_OUTPUT THREAD_PRIORITY_ABOVE_NORMAL
77 # define VLC_THREAD_PRIORITY_HIGHEST THREAD_PRIORITY_TIME_CRITICAL
79 static inline int vlc_poll(struct pollfd
*fds
, unsigned nfds
, int timeout
)
84 val
= poll(fds
, nfds
, timeout
);
89 # define poll(u,n,t) vlc_poll(u, n, t)
91 #elif defined (__OS2__)
94 typedef struct vlc_thread
*vlc_thread_t
;
95 #define VLC_THREAD_CANCELED NULL
97 typedef unsigned long vlc_osthread_t
;
98 #define vlc_thread_equal(a,b) ((a) == (b))
100 #define LIBVLC_NEED_RWLOCK
106 #define VLC_STATIC_ONCE { 0, VLC_STATIC_MUTEX }
107 typedef struct vlc_threadvar
*vlc_threadvar_t
;
108 typedef struct vlc_timer
*vlc_timer_t
;
110 # define VLC_THREAD_PRIORITY_LOW 0
111 # define VLC_THREAD_PRIORITY_INPUT \
112 MAKESHORT(PRTYD_MAXIMUM / 2, PRTYC_REGULAR)
113 # define VLC_THREAD_PRIORITY_AUDIO MAKESHORT(PRTYD_MAXIMUM, PRTYC_REGULAR)
114 # define VLC_THREAD_PRIORITY_VIDEO 0
115 # define VLC_THREAD_PRIORITY_OUTPUT \
116 MAKESHORT(PRTYD_MAXIMUM / 2, PRTYC_REGULAR)
117 # define VLC_THREAD_PRIORITY_HIGHEST MAKESHORT(0, PRTYC_TIMECRITICAL)
119 # define pthread_sigmask sigprocmask
121 static inline int vlc_poll (struct pollfd
*fds
, unsigned nfds
, int timeout
)
123 static int (*vlc_poll_os2
)(struct pollfd
*, unsigned, int) = NULL
;
128 CHAR szFailed
[CCHMAXPATH
];
130 if (DosLoadModule(szFailed
, sizeof(szFailed
), "vlccore", &hmod
))
133 if (DosQueryProcAddr(hmod
, 0, "_vlc_poll_os2", (PFN
*)&vlc_poll_os2
))
137 return (*vlc_poll_os2
)(fds
, nfds
, timeout
);
139 # define poll(u,n,t) vlc_poll(u, n, t)
141 #elif defined (__ANDROID__) /* pthreads subset without pthread_cancel() */
143 # include <pthread.h>
145 # define LIBVLC_USE_PTHREAD_CLEANUP 1
146 # define LIBVLC_NEED_SLEEP
147 # define LIBVLC_NEED_RWLOCK
149 typedef struct vlc_thread
*vlc_thread_t
;
150 #define VLC_THREAD_CANCELED NULL
151 typedef pthread_t vlc_osthread_t
;
152 #define vlc_thread_equal(a,b) pthread_equal(a,b)
153 typedef pthread_once_t vlc_once_t
;
154 #define VLC_STATIC_ONCE PTHREAD_ONCE_INIT
155 typedef pthread_key_t vlc_threadvar_t
;
156 typedef struct vlc_timer
*vlc_timer_t
;
158 # define VLC_THREAD_PRIORITY_LOW 0
159 # define VLC_THREAD_PRIORITY_INPUT 0
160 # define VLC_THREAD_PRIORITY_AUDIO 0
161 # define VLC_THREAD_PRIORITY_VIDEO 0
162 # define VLC_THREAD_PRIORITY_OUTPUT 0
163 # define VLC_THREAD_PRIORITY_HIGHEST 0
165 static inline int vlc_poll (struct pollfd
*fds
, unsigned nfds
, int timeout
)
171 int ugly_timeout
= ((unsigned)timeout
>= 50) ? 50 : timeout
;
173 timeout
-= ugly_timeout
;
176 val
= poll (fds
, nfds
, ugly_timeout
);
178 while (val
== 0 && timeout
!= 0);
183 # define poll(u,n,t) vlc_poll(u, n, t)
185 #elif defined (__APPLE__)
186 # define _APPLE_C_SOURCE 1 /* Proper pthread semantics on OSX */
188 # include <pthread.h>
189 /* Unnamed POSIX semaphores not supported on Mac OS X */
190 # include <mach/semaphore.h>
191 # include <mach/task.h>
192 # define LIBVLC_USE_PTHREAD_CLEANUP 1
194 typedef pthread_t vlc_thread_t
;
195 #define VLC_THREAD_CANCELED PTHREAD_CANCELED
196 typedef pthread_t vlc_osthread_t
;
197 #define vlc_thread_equal(a,b) pthread_equal(a,b)
198 typedef pthread_rwlock_t vlc_rwlock_t
;
199 #define VLC_STATIC_RWLOCK PTHREAD_RWLOCK_INITIALIZER
200 typedef pthread_once_t vlc_once_t
;
201 #define VLC_STATIC_ONCE PTHREAD_ONCE_INIT
202 typedef pthread_key_t vlc_threadvar_t
;
203 typedef struct vlc_timer
*vlc_timer_t
;
205 # define VLC_THREAD_PRIORITY_LOW 0
206 # define VLC_THREAD_PRIORITY_INPUT 22
207 # define VLC_THREAD_PRIORITY_AUDIO 22
208 # define VLC_THREAD_PRIORITY_VIDEO 0
209 # define VLC_THREAD_PRIORITY_OUTPUT 22
210 # define VLC_THREAD_PRIORITY_HIGHEST 22
212 #else /* POSIX threads */
213 # include <unistd.h> /* _POSIX_SPIN_LOCKS */
214 # include <pthread.h>
217 * Whether LibVLC threads are based on POSIX threads.
219 # define LIBVLC_USE_PTHREAD 1
222 * Whether LibVLC thread cancellation is based on POSIX threads.
224 # define LIBVLC_USE_PTHREAD_CLEANUP 1
235 * Return value of a canceled thread.
237 #define VLC_THREAD_CANCELED PTHREAD_CANCELED
239 typedef pthread_t vlc_osthread_t
;
240 #define vlc_thread_equal(a,b) pthread_equal(a,b)
245 * Storage space for a slim reader/writer lock.
249 typedef pthread_rwlock_t vlc_rwlock_t
;
252 * Static initializer for (static) read/write lock.
256 #define VLC_STATIC_RWLOCK PTHREAD_RWLOCK_INITIALIZER
259 * One-time initialization.
261 * A one-time initialization object must always be initialized assigned to
262 * \ref VLC_STATIC_ONCE before use.
264 typedef pthread_once_t vlc_once_t
;
267 * Static initializer for one-time initialization.
269 #define VLC_STATIC_ONCE PTHREAD_ONCE_INIT
272 * Thread-local key handle.
276 typedef pthread_key_t vlc_threadvar_t
;
279 * Threaded timer handle.
283 typedef struct vlc_timer
*vlc_timer_t
;
285 # define VLC_THREAD_PRIORITY_LOW 0
286 # define VLC_THREAD_PRIORITY_INPUT 10
287 # define VLC_THREAD_PRIORITY_AUDIO 5
288 # define VLC_THREAD_PRIORITY_VIDEO 0
289 # define VLC_THREAD_PRIORITY_OUTPUT 15
290 # define VLC_THREAD_PRIORITY_HIGHEST 20
295 * \defgroup mutex Mutual exclusion locks
301 * Storage space for a mutual exclusion lock.
309 atomic_uint recursion
;
310 const void *_Atomic owner
;
315 unsigned int recursion
;
322 * Static initializer for (static) mutex.
324 * \note This only works in C code.
325 * In C++, consider using a global \ref vlc::threads::mutex instance instead.
327 #define VLC_STATIC_MUTEX { \
328 .value = ATOMIC_VAR_INIT(0), \
329 .recursion = ATOMIC_VAR_INIT(0), \
330 .owner = ATOMIC_VAR_INIT(NULL), \
334 * Initializes a fast mutex.
336 * Recursive locking of a fast mutex is undefined behaviour. (In debug builds,
337 * recursive locking will cause an assertion failure.)
339 VLC_API
void vlc_mutex_init(vlc_mutex_t
*);
342 * Initializes a recursive mutex.
343 * \warning This is strongly discouraged. Please use normal mutexes.
345 VLC_API
void vlc_mutex_init_recursive(vlc_mutex_t
*);
350 * If needed, this waits for any other thread to release it.
352 * \warning Beware of deadlocks when locking multiple mutexes at the same time,
353 * or when using mutexes from callbacks.
355 * \note This function is not a cancellation point.
357 VLC_API
void vlc_mutex_lock(vlc_mutex_t
*);
360 * Tries to acquire a mutex.
362 * This function acquires the mutex if and only if it is not currently held by
363 * another thread. This function never sleeps and can be used in delay-critical
366 * \note This function is not a cancellation point.
368 * \warning If this function fails, then the mutex is held... by another
369 * thread. The calling thread must deal with the error appropriately. That
370 * typically implies postponing the operations that would have required the
371 * mutex. If the thread cannot defer those operations, then it must use
372 * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
374 * @return 0 if the mutex could be acquired, an error code otherwise.
376 VLC_API
int vlc_mutex_trylock( vlc_mutex_t
* ) VLC_USED
;
381 * If the mutex is not held by the calling thread, the behaviour is undefined.
383 * \note This function is not a cancellation point.
385 VLC_API
void vlc_mutex_unlock(vlc_mutex_t
*);
388 * Checks if a mutex is locked.
390 * Do not use this function directly. Use vlc_mutex_assert() instead.
393 * This function has no effects.
394 * It is only meant to be use in run-time assertions.
396 * @warning This function might not return correct results in non-debug builds.
398 * @retval false the mutex is not locked by the calling thread
399 * @retval true the mutex is locked by the calling thread
401 VLC_API
bool vlc_mutex_held(const vlc_mutex_t
*) VLC_USED
;
404 * Asserts that a mutex is locked by the calling thread.
406 #define vlc_mutex_assert(m) assert(vlc_mutex_held(m))
411 * \defgroup condvar Condition variables
413 * The condition variable is the most common and generic mean for threads to
414 * wait for events triggered by other threads.
416 * See also POSIX @c pthread_cond_t .
420 struct vlc_cond_waiter
;
423 * Condition variable.
425 * Storage space for a thread condition variable.
429 struct vlc_cond_waiter
*head
;
434 * Static initializer for (static) condition variable.
437 * The condition variable will use the default clock, which is OS-dependent.
438 * Therefore, where timed waits are necessary the condition variable should
439 * always be initialized dynamically explicit instead of using this
442 #define VLC_STATIC_COND { NULL, VLC_STATIC_MUTEX }
445 * Initializes a condition variable.
447 VLC_API
void vlc_cond_init(vlc_cond_t
*);
450 * Initializes a condition variable (wall clock).
452 * This function initializes a condition variable for timed waiting using the
453 * UTC wall clock time. The time reference is the same as with time() and with
454 * timespec_get() and TIME_UTC.
455 * vlc_cond_timedwait_daytime() must be instead of
456 * vlc_cond_timedwait() for actual waiting.
458 void vlc_cond_init_daytime(vlc_cond_t
*);
461 * Wakes up one thread waiting on a condition variable.
463 * If any thread is currently waiting on the condition variable, at least one
464 * of those threads will be woken up. Otherwise, this function has no effects.
466 * \note This function is not a cancellation point.
468 VLC_API
void vlc_cond_signal(vlc_cond_t
*);
471 * Wakes up all threads waiting on a condition variable.
473 * \note This function is not a cancellation point.
475 VLC_API
void vlc_cond_broadcast(vlc_cond_t
*);
478 * Waits on a condition variable.
480 * The calling thread will be suspended until another thread calls
481 * vlc_cond_signal() or vlc_cond_broadcast() on the same condition variable,
482 * the thread is cancelled with vlc_cancel(), or the system causes a
483 * <em>spurious</em> unsolicited wake-up.
485 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
486 * a recursive mutex. Although it is possible to use the same mutex for
487 * multiple condition, it is not valid to use different mutexes for the same
488 * condition variable at the same time from different threads.
490 * The canonical way to use a condition variable to wait for event foobar is:
492 vlc_mutex_lock(&lock);
493 mutex_cleanup_push(&lock); // release the mutex in case of cancellation
496 vlc_cond_wait(&wait, &lock);
498 // -- foobar is now true, do something about it here --
501 vlc_mutex_unlock(&lock);
504 * \note This function is a cancellation point. In case of thread cancellation,
505 * the mutex is always locked before cancellation proceeds.
507 * \param cond condition variable to wait on
508 * \param mutex mutex which is unlocked while waiting,
509 * then locked again when waking up.
511 VLC_API
void vlc_cond_wait(vlc_cond_t
*cond
, vlc_mutex_t
*mutex
);
514 * Waits on a condition variable up to a certain date.
516 * This works like vlc_cond_wait() but with an additional time-out.
517 * The time-out is expressed as an absolute timestamp using the same arbitrary
518 * time reference as the vlc_tick_now() and vlc_tick_wait() functions.
520 * \note This function is a cancellation point. In case of thread cancellation,
521 * the mutex is always locked before cancellation proceeds.
523 * \param cond condition variable to wait on
524 * \param mutex mutex which is unlocked while waiting,
525 * then locked again when waking up
526 * \param deadline <b>absolute</b> timeout
528 * \warning If the variable was initialized with vlc_cond_init_daytime(), or
529 * was statically initialized with \ref VLC_STATIC_COND, the time reference
530 * used by this function is unspecified (depending on the implementation, it
531 * might be the Unix epoch or the vlc_tick_now() clock).
533 * \return 0 if the condition was signaled, an error code in case of timeout.
535 VLC_API
int vlc_cond_timedwait(vlc_cond_t
*cond
, vlc_mutex_t
*mutex
,
536 vlc_tick_t deadline
);
538 int vlc_cond_timedwait_daytime(vlc_cond_t
*, vlc_mutex_t
*, time_t);
543 * \defgroup semaphore Semaphores
545 * The semaphore is the simplest thread synchronization primitive, consisting
546 * of a simple counter.
548 * See also POSIX @c sem_t .
555 * Storage space for a thread-safe semaphore.
568 * Initializes a semaphore.
570 * @param count initial semaphore value (typically 0)
572 VLC_API
void vlc_sem_init(vlc_sem_t
*, unsigned count
);
575 * Increments the value of a semaphore.
577 * \note This function is not a cancellation point.
579 * \return 0 on success, EOVERFLOW in case of integer overflow.
581 VLC_API
int vlc_sem_post(vlc_sem_t
*);
584 * Waits on a semaphore.
586 * This function atomically waits for the semaphore to become non-zero then
587 * decrements it, and returns. If the semaphore is non-zero on entry, it is
588 * immediately decremented.
590 * \note This function may be a point of cancellation.
592 VLC_API
void vlc_sem_wait(vlc_sem_t
*);
595 * Waits on a semaphore within a deadline.
597 * This function waits for the semaphore just like vlc_sem_wait(), but only
598 * up to a given deadline.
600 * \param sem semaphore to wait for
601 * \param deadline deadline to wait until
603 * \retval 0 the semaphore was decremented
604 * \retval ETIMEDOUT the deadline was reached
606 VLC_API
int vlc_sem_timedwait(vlc_sem_t
*sem
, vlc_tick_t deadline
) VLC_USED
;
611 * \defgroup rwlock Read/write locks
613 * Read/write locks are a type of thread synchronization primitive meant to
614 * protect access to data that is mostly read, and rarely written.
615 * As long as no threads tries to acquire the lock for "writing", any number of
616 * threads can acquire the lock for "reading".
618 * See also POSIX @c pthread_rwlock_t .
623 #ifdef LIBVLC_NEED_RWLOCK
624 typedef struct vlc_rwlock
630 # define VLC_STATIC_RWLOCK { VLC_STATIC_MUTEX, VLC_STATIC_COND, 0 }
634 * Initializes a read/write lock.
636 * After use, a read/write lock must be deinitialized with
637 * vlc_rwlock_destroy().
639 VLC_API
void vlc_rwlock_init(vlc_rwlock_t
*);
642 * Destroys an initialized unused read/write lock.
644 VLC_API
void vlc_rwlock_destroy(vlc_rwlock_t
*);
647 * Acquires a read/write lock for reading.
649 * \note Recursion is allowed.
650 * \note This function may be a point of cancellation.
652 VLC_API
void vlc_rwlock_rdlock(vlc_rwlock_t
*);
655 * Acquires a read/write lock for writing. Recursion is not allowed.
656 * \note This function may be a point of cancellation.
658 VLC_API
void vlc_rwlock_wrlock(vlc_rwlock_t
*);
661 * Releases a read/write lock.
663 * The calling thread must hold the lock. Otherwise behaviour is undefined.
665 * \note This function is not a cancellation point.
667 VLC_API
void vlc_rwlock_unlock(vlc_rwlock_t
*);
672 * Executes a function one time.
674 * The first time this function is called with a given one-time initialization
675 * object, it executes the provided callback.
676 * Any further call with the same object will be a no-op.
678 * In the corner case that the first time execution is ongoing in another
679 * thread, then the function will wait for completion on the other thread
680 * (and then synchronize memory) before it returns.
681 * This ensures that, no matter what, the callback has been executed exactly
682 * once and its side effects are visible after the function returns.
684 * \param once a one-time initialization object
685 * \param cb callback to execute (the first time)
687 VLC_API
void vlc_once(vlc_once_t
*restrict once
, void (*cb
)(void));
690 * \defgroup threadvar Thread-specific variables
694 * Allocates a thread-specific variable.
696 * @param key where to store the thread-specific variable handle
697 * @param destr a destruction callback. It is called whenever a thread exits
698 * and the thread-specific variable has a non-NULL value.
700 * @return 0 on success, a system error code otherwise.
701 * This function can actually fail: on most systems, there is a fixed limit to
702 * the number of thread-specific variables in a given process.
704 VLC_API
int vlc_threadvar_create(vlc_threadvar_t
*key
, void (*destr
) (void *));
707 * Deallocates a thread-specific variable.
709 VLC_API
void vlc_threadvar_delete(vlc_threadvar_t
*);
712 * Sets a thread-specific variable.
714 * \param key thread-local variable key (created with vlc_threadvar_create())
715 * \param value new value for the variable for the calling thread
716 * \return 0 on success, a system error code otherwise.
718 VLC_API
int vlc_threadvar_set(vlc_threadvar_t key
, void *value
);
721 * Gets the value of a thread-local variable for the calling thread.
722 * This function cannot fail.
724 * \return the value associated with the given variable for the calling
725 * or NULL if no value was set.
727 VLC_API
void *vlc_threadvar_get(vlc_threadvar_t
);
732 * Waits on an address.
734 * Puts the calling thread to sleep if a specific unsigned 32-bits value is
735 * stored at a specified address. The thread will sleep until it is woken up by
736 * a call to vlc_atomic_notify_one() or vlc_atomic_notify_all() in another
737 * thread, or spuriously.
739 * If the value does not match, do nothing and return immediately.
741 * \param addr address to check for
742 * \param val value to match at the address
744 void vlc_atomic_wait(void *addr
, unsigned val
);
747 * Waits on an address with a time-out.
749 * This function operates as vlc_atomic_wait() but provides an additional
750 * time-out. If the deadline is reached, the thread resumes and the function
753 * \param addr address to check for
754 * \param val value to match at the address
755 * \param deadline deadline to wait until
757 * \retval 0 the function was woken up before the time-out
758 * \retval ETIMEDOUT the deadline was reached
760 int vlc_atomic_timedwait(void *addr
, unsigned val
, vlc_tick_t deadline
);
762 int vlc_atomic_timedwait_daytime(void *addr
, unsigned val
, time_t deadline
);
765 * Wakes up one thread on an address.
767 * Wakes up (at least) one of the thread sleeping on the specified address.
768 * The address must be equal to the first parameter given by at least one
769 * thread sleeping within the vlc_atomic_wait() or vlc_atomic_timedwait()
770 * functions. If no threads are found, this function does nothing.
772 * \param addr address identifying which threads may be woken up
774 void vlc_atomic_notify_one(void *addr
);
777 * Wakes up all thread on an address.
779 * Wakes up all threads sleeping on the specified address (if any).
780 * Any thread sleeping within a call to vlc_atomic_wait() or
781 * vlc_atomic_timedwait() with the specified address as first call parameter
784 * \param addr address identifying which threads to wake up
786 void vlc_atomic_notify_all(void *addr
);
789 * Creates and starts a new thread.
791 * The thread must be <i>joined</i> with vlc_join() to reclaim resources
792 * when it is not needed anymore.
794 * @param th storage space for the handle of the new thread (cannot be NULL)
796 * @param entry entry point for the thread
797 * @param data data parameter given to the entry point
798 * @param priority thread priority value
799 * @return 0 on success, a standard error code on error.
800 * @note In case of error, the value of *th is undefined.
802 VLC_API
int vlc_clone(vlc_thread_t
*th
, void *(*entry
)(void *), void *data
,
803 int priority
) VLC_USED
;
806 * Marks a thread as cancelled.
808 * Next time the target thread reaches a cancellation point (while not having
809 * disabled cancellation), it will run its cancellation cleanup handler, the
810 * thread variable destructors, and terminate.
812 * vlc_join() must be used regardless of a thread being cancelled or not, to
813 * avoid leaking resources.
815 VLC_API
void vlc_cancel(vlc_thread_t
);
818 * Waits for a thread to complete (if needed), then destroys it.
820 * \note This is a cancellation point. In case of cancellation, the thread is
823 * \warning A thread cannot join itself (normally VLC will abort if this is
824 * attempted). Also a detached thread <b>cannot</b> be joined.
826 * @param th thread handle
827 * @param result [OUT] pointer to write the thread return value or NULL
829 VLC_API
void vlc_join(vlc_thread_t th
, void **result
);
832 * Disables thread cancellation.
834 * This functions saves the current cancellation state (enabled or disabled),
835 * then disables cancellation for the calling thread. It must be called before
836 * entering a piece of code that is not cancellation-safe, unless it can be
837 * proven that the calling thread will not be cancelled.
839 * \note This function is not a cancellation point.
841 * \return Previous cancellation state (opaque value for vlc_restorecancel()).
843 VLC_API
int vlc_savecancel(void);
846 * Restores the cancellation state.
848 * This function restores the cancellation state of the calling thread to
849 * a state previously saved by vlc_savecancel().
851 * \note This function is not a cancellation point.
853 * \param state previous state as returned by vlc_savecancel().
855 VLC_API
void vlc_restorecancel(int state
);
857 typedef struct vlc_cleanup_t vlc_cleanup_t
;
860 * Internal handler for thread cancellation.
862 * Do not call this function directly. Use wrapper macros instead:
863 * vlc_cleanup_push(), vlc_cleanup_pop().
865 VLC_API
void vlc_control_cancel(vlc_cleanup_t
*);
870 * This function returns the thread handle of the calling thread.
871 * This works even if the thread was <b>not</b> created with vlc_clone().
872 * As a consequence, depending on the platform, this might or might not be the
873 * same as the @ref vlc_thread_t thread handle returned by vlc_clone().
875 * Also depending on the platform, this might be an integer type, a pointer
876 * type, or a compound type of any (reasonable) size. To compare two thread
877 * handles, use the vlc_thread_equal() macro, not a hand-coded comparison.
878 * Comparing the calling thread for equality with another thread is in fact
879 * pretty much the only purpose of this function.
881 * \note If you need an integer identifier, use vlc_thread_id() instead.
883 * \return the OS run-time thread handle
885 VLC_API vlc_osthread_t
vlc_thread_self(void) VLC_USED
;
890 * This function returns the identifier of the calling thread. The identifier
891 * cannot change for the entire duration of the thread, and no other thread can
892 * have the same identifier at the same time in the same process. Typically,
893 * the identifier is also unique across all running threads of all existing
894 * processes, but that depends on the operating system.
896 * There are no particular semantics to the thread ID with LibVLC.
897 * It is provided mainly for tracing and debugging.
899 * See also vlc_thread_self().
901 * \warning This function is not currently implemented on all supported
902 * platforms. Where not implemented, it returns (unsigned long)-1.
904 * \return the thread identifier (or -1 if unimplemented)
906 VLC_API
unsigned long vlc_thread_id(void) VLC_USED
;
909 * Precision monotonic clock.
911 * In principles, the clock has a precision of 1 MHz. But the actual resolution
912 * may be much lower, especially when it comes to sleeping with vlc_tick_wait() or
913 * vlc_tick_sleep(). Most general-purpose operating systems provide a resolution of
914 * only 100 to 1000 Hz.
916 * \warning The origin date (time value "zero") is not specified. It is
917 * typically the time the kernel started, but this is platform-dependent.
918 * If you need wall clock time, use gettimeofday() instead.
920 * \return a timestamp in microseconds.
922 VLC_API vlc_tick_t
vlc_tick_now(void);
925 * Waits until a deadline.
927 * \param deadline timestamp to wait for (\ref vlc_tick_now())
929 * \note The deadline may be exceeded due to OS scheduling.
930 * \note This function is a cancellation point.
932 VLC_API
void vlc_tick_wait(vlc_tick_t deadline
);
935 * Waits for an interval of time.
937 * \param delay how long to wait (in microseconds)
939 * \note The delay may be exceeded due to OS scheduling.
940 * \note This function is a cancellation point.
942 VLC_API
void vlc_tick_sleep(vlc_tick_t delay
);
944 #define VLC_HARD_MIN_SLEEP VLC_TICK_FROM_MS(10) /* 10 milliseconds = 1 tick at 100Hz */
945 #define VLC_SOFT_MIN_SLEEP VLC_TICK_FROM_SEC(9) /* 9 seconds */
947 #if defined (__GNUC__) && !defined (__clang__)
948 /* Linux has 100, 250, 300 or 1000Hz
950 * HZ=100 by default on FreeBSD, but some architectures use a 1000Hz timer
954 __attribute__((unused
))
955 __attribute__((noinline
))
956 __attribute__((error("sorry, cannot sleep for such short a time")))
957 vlc_tick_t
impossible_delay( vlc_tick_t delay
)
960 return VLC_HARD_MIN_SLEEP
;
964 __attribute__((unused
))
965 __attribute__((noinline
))
966 __attribute__((warning("use proper event handling instead of short delay")))
967 vlc_tick_t
harmful_delay( vlc_tick_t delay
)
972 # define check_delay( d ) \
973 ((__builtin_constant_p(d < VLC_HARD_MIN_SLEEP) \
974 && (d < VLC_HARD_MIN_SLEEP)) \
975 ? impossible_delay(d) \
976 : ((__builtin_constant_p(d < VLC_SOFT_MIN_SLEEP) \
977 && (d < VLC_SOFT_MIN_SLEEP)) \
982 __attribute__((unused
))
983 __attribute__((noinline
))
984 __attribute__((error("deadlines can not be constant")))
985 vlc_tick_t
impossible_deadline( vlc_tick_t deadline
)
990 # define check_deadline( d ) \
991 (__builtin_constant_p(d) ? impossible_deadline(d) : d)
993 # define check_delay(d) (d)
994 # define check_deadline(d) (d)
997 #define vlc_tick_sleep(d) vlc_tick_sleep(check_delay(d))
998 #define vlc_tick_wait(d) vlc_tick_wait(check_deadline(d))
1001 * \defgroup timer Asynchronous/threaded timers
1005 * Initializes an asynchronous timer.
1007 * \param id pointer to timer to be initialized
1008 * \param func function that the timer will call
1009 * \param data parameter for the timer function
1010 * \return 0 on success, a system error code otherwise.
1012 * \warning Asynchronous timers are processed from an unspecified thread.
1013 * \note Multiple occurrences of a single interval timer are serialized:
1014 * they cannot run concurrently.
1016 VLC_API
int vlc_timer_create(vlc_timer_t
*id
, void (*func
)(void *), void *data
)
1020 * Destroys an initialized timer.
1022 * If needed, the timer is first disarmed. Behaviour is undefined if the
1023 * specified timer is not initialized.
1025 * \warning This function <b>must</b> be called before the timer data can be
1026 * freed and before the timer callback function can be unmapped/unloaded.
1028 * \param timer timer to destroy
1030 VLC_API
void vlc_timer_destroy(vlc_timer_t timer
);
1032 #define VLC_TIMER_DISARM (0)
1033 #define VLC_TIMER_FIRE_ONCE (0)
1036 * Arms or disarms an initialized timer.
1038 * This functions overrides any previous call to itself.
1040 * \note A timer can fire later than requested due to system scheduling
1041 * limitations. An interval timer can fail to trigger sometimes, either because
1042 * the system is busy or suspended, or because a previous iteration of the
1043 * timer is still running. See also vlc_timer_getoverrun().
1045 * \param timer initialized timer
1046 * \param absolute the timer value origin is the same as vlc_tick_now() if true,
1047 * the timer value is relative to now if false.
1048 * \param value zero to disarm the timer, otherwise the initial time to wait
1049 * before firing the timer.
1050 * \param interval zero to fire the timer just once, otherwise the timer
1051 * repetition interval.
1053 VLC_API
void vlc_timer_schedule(vlc_timer_t timer
, bool absolute
,
1054 vlc_tick_t value
, vlc_tick_t interval
);
1056 static inline void vlc_timer_disarm(vlc_timer_t timer
)
1058 vlc_timer_schedule( timer
, false, VLC_TIMER_DISARM
, 0 );
1061 static inline void vlc_timer_schedule_asap(vlc_timer_t timer
, vlc_tick_t interval
)
1063 vlc_timer_schedule(timer
, false, 1, interval
);
1067 * Fetches and resets the overrun counter for a timer.
1069 * This functions returns the number of times that the interval timer should
1070 * have fired, but the callback was not invoked due to scheduling problems.
1071 * The call resets the counter to zero.
1073 * \param timer initialized timer
1074 * \return the timer overrun counter (typically zero)
1076 VLC_API
unsigned vlc_timer_getoverrun(vlc_timer_t
) VLC_USED
;
1083 * \return number of available (logical) CPUs.
1085 VLC_API
unsigned vlc_GetCPUCount(void);
1087 #if defined (LIBVLC_USE_PTHREAD_CLEANUP)
1089 * Registers a thread cancellation handler.
1091 * This pushes a function to run if the thread is cancelled (or otherwise
1092 * exits prematurely).
1094 * If multiple procedures are registered,
1095 * they are handled in last-in first-out order.
1097 * \note Any call to vlc_cleanup_push() <b>must</b> paired with a call to
1098 * vlc_cleanup_pop().
1099 * \warning Branching into or out of the block between these two function calls
1100 * is not allowed (read: it will likely crash the whole process).
1102 * \param routine procedure to call if the thread ends
1103 * \param arg argument for the procedure
1105 # define vlc_cleanup_push( routine, arg ) pthread_cleanup_push (routine, arg)
1108 * Unregisters the last cancellation handler.
1110 * This pops the cancellation handler that was last pushed with
1111 * vlc_cleanup_push() in the calling thread.
1113 # define vlc_cleanup_pop( ) pthread_cleanup_pop (0)
1115 #else /* !LIBVLC_USE_PTHREAD_CLEANUP */
1116 struct vlc_cleanup_t
1118 vlc_cleanup_t
*next
;
1119 void (*proc
) (void *);
1123 # ifndef __cplusplus
1124 /* This macros opens a code block on purpose: It reduces the chance of
1125 * not pairing the push and pop. It also matches the POSIX Thread internals.
1126 * That way, Win32 developers will not accidentally break other platforms.
1128 # define vlc_cleanup_push( routine, arg ) \
1130 vlc_control_cancel(&(vlc_cleanup_t){ NULL, routine, arg })
1132 # define vlc_cleanup_pop( ) \
1133 vlc_control_cancel (NULL); \
1136 # define vlc_cleanup_push(routine, arg) \
1137 static_assert(false, "don't use vlc_cleanup_push in portable C++ code")
1138 # define vlc_cleanup_pop() \
1139 static_assert(false, "don't use vlc_cleanup_pop in portable C++ code")
1142 #endif /* !LIBVLC_USE_PTHREAD_CLEANUP */
1144 static inline void vlc_cleanup_lock (void *lock
)
1146 vlc_mutex_unlock ((vlc_mutex_t
*)lock
);
1148 #define mutex_cleanup_push( lock ) vlc_cleanup_push (vlc_cleanup_lock, lock)
1151 void vlc_cancel_addr_set(atomic_uint
*addr
);
1152 void vlc_cancel_addr_clear(atomic_uint
*addr
);
1155 * Helper C++ class to lock a mutex.
1157 * The mutex is locked when the object is created, and unlocked when the object
1160 class vlc_mutex_locker
1165 vlc_mutex_locker (vlc_mutex_t
*m
) : lock (m
)
1167 vlc_mutex_lock (lock
);
1170 ~vlc_mutex_locker (void)
1172 vlc_mutex_unlock (lock
);
1180 VLC_AVCODEC_MUTEX
= 0,
1187 /* Insert new entry HERE */
1192 * Internal handler for global mutexes.
1194 * Do not use this function directly. Use helper macros instead:
1195 * vlc_global_lock(), vlc_global_unlock().
1197 VLC_API
void vlc_global_mutex(unsigned, bool);
1200 * Acquires a global mutex.
1202 #define vlc_global_lock( n ) vlc_global_mutex(n, true)
1205 * Releases a global mutex.
1207 #define vlc_global_unlock( n ) vlc_global_mutex(n, false)
1211 #endif /* !_VLC_THREADS_H */