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 INIT_ONCE vlc_once_t
;
65 #define VLC_STATIC_ONCE INIT_ONCE_STATIC_INIT
66 typedef struct vlc_threadvar
*vlc_threadvar_t
;
67 typedef struct vlc_timer
*vlc_timer_t
;
69 # define VLC_THREAD_PRIORITY_LOW 0
70 # define VLC_THREAD_PRIORITY_INPUT THREAD_PRIORITY_ABOVE_NORMAL
71 # define VLC_THREAD_PRIORITY_AUDIO THREAD_PRIORITY_HIGHEST
72 # define VLC_THREAD_PRIORITY_VIDEO 0
73 # define VLC_THREAD_PRIORITY_OUTPUT THREAD_PRIORITY_ABOVE_NORMAL
74 # define VLC_THREAD_PRIORITY_HIGHEST THREAD_PRIORITY_TIME_CRITICAL
76 static inline int vlc_poll(struct pollfd
*fds
, unsigned nfds
, int timeout
)
81 val
= poll(fds
, nfds
, timeout
);
86 # define poll(u,n,t) vlc_poll(u, n, t)
88 #elif defined (__OS2__)
91 typedef struct vlc_thread
*vlc_thread_t
;
92 #define VLC_THREAD_CANCELED NULL
94 #define LIBVLC_NEED_RWLOCK
100 #define VLC_STATIC_ONCE { 0, VLC_STATIC_MUTEX }
101 typedef struct vlc_threadvar
*vlc_threadvar_t
;
102 typedef struct vlc_timer
*vlc_timer_t
;
104 # define VLC_THREAD_PRIORITY_LOW 0
105 # define VLC_THREAD_PRIORITY_INPUT \
106 MAKESHORT(PRTYD_MAXIMUM / 2, PRTYC_REGULAR)
107 # define VLC_THREAD_PRIORITY_AUDIO MAKESHORT(PRTYD_MAXIMUM, PRTYC_REGULAR)
108 # define VLC_THREAD_PRIORITY_VIDEO 0
109 # define VLC_THREAD_PRIORITY_OUTPUT \
110 MAKESHORT(PRTYD_MAXIMUM / 2, PRTYC_REGULAR)
111 # define VLC_THREAD_PRIORITY_HIGHEST MAKESHORT(0, PRTYC_TIMECRITICAL)
113 # define pthread_sigmask sigprocmask
115 static inline int vlc_poll (struct pollfd
*fds
, unsigned nfds
, int timeout
)
117 static int (*vlc_poll_os2
)(struct pollfd
*, unsigned, int) = NULL
;
122 CHAR szFailed
[CCHMAXPATH
];
124 if (DosLoadModule(szFailed
, sizeof(szFailed
), "vlccore", &hmod
))
127 if (DosQueryProcAddr(hmod
, 0, "_vlc_poll_os2", (PFN
*)&vlc_poll_os2
))
131 return (*vlc_poll_os2
)(fds
, nfds
, timeout
);
133 # define poll(u,n,t) vlc_poll(u, n, t)
135 #elif defined (__ANDROID__) /* pthreads subset without pthread_cancel() */
137 # include <pthread.h>
139 # define LIBVLC_USE_PTHREAD_CLEANUP 1
140 # define LIBVLC_NEED_SLEEP
141 # define LIBVLC_NEED_RWLOCK
143 typedef struct vlc_thread
*vlc_thread_t
;
144 #define VLC_THREAD_CANCELED NULL
145 typedef pthread_once_t vlc_once_t
;
146 #define VLC_STATIC_ONCE PTHREAD_ONCE_INIT
147 typedef pthread_key_t vlc_threadvar_t
;
148 typedef struct vlc_timer
*vlc_timer_t
;
150 # define VLC_THREAD_PRIORITY_LOW 0
151 # define VLC_THREAD_PRIORITY_INPUT 0
152 # define VLC_THREAD_PRIORITY_AUDIO 0
153 # define VLC_THREAD_PRIORITY_VIDEO 0
154 # define VLC_THREAD_PRIORITY_OUTPUT 0
155 # define VLC_THREAD_PRIORITY_HIGHEST 0
157 static inline int vlc_poll (struct pollfd
*fds
, unsigned nfds
, int timeout
)
163 int ugly_timeout
= ((unsigned)timeout
>= 50) ? 50 : timeout
;
165 timeout
-= ugly_timeout
;
168 val
= poll (fds
, nfds
, ugly_timeout
);
170 while (val
== 0 && timeout
!= 0);
175 # define poll(u,n,t) vlc_poll(u, n, t)
177 #elif defined (__APPLE__)
178 # define _APPLE_C_SOURCE 1 /* Proper pthread semantics on OSX */
180 # include <pthread.h>
181 /* Unnamed POSIX semaphores not supported on Mac OS X */
182 # include <mach/semaphore.h>
183 # include <mach/task.h>
184 # define LIBVLC_USE_PTHREAD_CLEANUP 1
186 typedef pthread_t vlc_thread_t
;
187 #define VLC_THREAD_CANCELED PTHREAD_CANCELED
188 typedef pthread_rwlock_t vlc_rwlock_t
;
189 #define VLC_STATIC_RWLOCK PTHREAD_RWLOCK_INITIALIZER
190 typedef pthread_once_t vlc_once_t
;
191 #define VLC_STATIC_ONCE PTHREAD_ONCE_INIT
192 typedef pthread_key_t vlc_threadvar_t
;
193 typedef struct vlc_timer
*vlc_timer_t
;
195 # define VLC_THREAD_PRIORITY_LOW 0
196 # define VLC_THREAD_PRIORITY_INPUT 22
197 # define VLC_THREAD_PRIORITY_AUDIO 22
198 # define VLC_THREAD_PRIORITY_VIDEO 0
199 # define VLC_THREAD_PRIORITY_OUTPUT 22
200 # define VLC_THREAD_PRIORITY_HIGHEST 22
202 #else /* POSIX threads */
203 # include <unistd.h> /* _POSIX_SPIN_LOCKS */
204 # include <pthread.h>
207 * Whether LibVLC threads are based on POSIX threads.
209 # define LIBVLC_USE_PTHREAD 1
212 * Whether LibVLC thread cancellation is based on POSIX threads.
214 # define LIBVLC_USE_PTHREAD_CLEANUP 1
225 * Return value of a canceled thread.
227 #define VLC_THREAD_CANCELED PTHREAD_CANCELED
232 * Storage space for a slim reader/writer lock.
236 typedef pthread_rwlock_t vlc_rwlock_t
;
239 * Static initializer for (static) read/write lock.
243 #define VLC_STATIC_RWLOCK PTHREAD_RWLOCK_INITIALIZER
246 * One-time initialization.
248 * A one-time initialization object must always be initialized assigned to
249 * \ref VLC_STATIC_ONCE before use.
251 typedef pthread_once_t vlc_once_t
;
254 * Static initializer for one-time initialization.
256 #define VLC_STATIC_ONCE PTHREAD_ONCE_INIT
259 * Thread-local key handle.
263 typedef pthread_key_t vlc_threadvar_t
;
266 * Threaded timer handle.
270 typedef struct vlc_timer
*vlc_timer_t
;
272 # define VLC_THREAD_PRIORITY_LOW 0
273 # define VLC_THREAD_PRIORITY_INPUT 10
274 # define VLC_THREAD_PRIORITY_AUDIO 5
275 # define VLC_THREAD_PRIORITY_VIDEO 0
276 # define VLC_THREAD_PRIORITY_OUTPUT 15
277 # define VLC_THREAD_PRIORITY_HIGHEST 20
282 * \defgroup mutex Mutual exclusion locks
288 * Storage space for a mutual exclusion lock.
296 atomic_uint recursion
;
297 _Atomic (const void *) owner
;
302 unsigned int recursion
;
309 * Static initializer for (static) mutex.
311 * \note This only works in C code.
312 * In C++, consider using a global \ref vlc::threads::mutex instance instead.
314 #define VLC_STATIC_MUTEX { \
315 .value = ATOMIC_VAR_INIT(0), \
316 .recursion = ATOMIC_VAR_INIT(0), \
317 .owner = ATOMIC_VAR_INIT(NULL), \
321 * Initializes a fast mutex.
323 * Recursive locking of a fast mutex is undefined behaviour. (In debug builds,
324 * recursive locking will cause an assertion failure.)
326 VLC_API
void vlc_mutex_init(vlc_mutex_t
*);
329 * Initializes a recursive mutex.
330 * \warning This is strongly discouraged. Please use normal mutexes.
332 VLC_API
void vlc_mutex_init_recursive(vlc_mutex_t
*);
337 * If needed, this waits for any other thread to release it.
339 * \warning Beware of deadlocks when locking multiple mutexes at the same time,
340 * or when using mutexes from callbacks.
342 * \note This function is not a cancellation point.
344 VLC_API
void vlc_mutex_lock(vlc_mutex_t
*);
347 * Tries to acquire a mutex.
349 * This function acquires the mutex if and only if it is not currently held by
350 * another thread. This function never sleeps and can be used in delay-critical
353 * \note This function is not a cancellation point.
355 * \warning If this function fails, then the mutex is held... by another
356 * thread. The calling thread must deal with the error appropriately. That
357 * typically implies postponing the operations that would have required the
358 * mutex. If the thread cannot defer those operations, then it must use
359 * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
361 * @return 0 if the mutex could be acquired, an error code otherwise.
363 VLC_API
int vlc_mutex_trylock( vlc_mutex_t
* ) VLC_USED
;
368 * If the mutex is not held by the calling thread, the behaviour is undefined.
370 * \note This function is not a cancellation point.
372 VLC_API
void vlc_mutex_unlock(vlc_mutex_t
*);
375 * Checks if a mutex is locked.
377 * Do not use this function directly. Use vlc_mutex_assert() instead.
380 * This function has no effects.
381 * It is only meant to be use in run-time assertions.
383 * @warning This function might not return correct results in non-debug builds.
385 * @retval false the mutex is not locked by the calling thread
386 * @retval true the mutex is locked by the calling thread
388 VLC_API
bool vlc_mutex_held(const vlc_mutex_t
*) VLC_USED
;
391 * Asserts that a mutex is locked by the calling thread.
393 #define vlc_mutex_assert(m) assert(vlc_mutex_held(m))
398 * \defgroup condvar Condition variables
400 * The condition variable is the most common and generic mean for threads to
401 * wait for events triggered by other threads.
403 * See also POSIX @c pthread_cond_t .
407 struct vlc_cond_waiter
;
410 * Condition variable.
412 * Storage space for a thread condition variable.
416 struct vlc_cond_waiter
*head
;
421 * Static initializer for (static) condition variable.
423 #define VLC_STATIC_COND { NULL, VLC_STATIC_MUTEX }
426 * Initializes a condition variable.
428 VLC_API
void vlc_cond_init(vlc_cond_t
*);
431 * Wakes up one thread waiting on a condition variable.
433 * If any thread is currently waiting on the condition variable, at least one
434 * of those threads will be woken up. Otherwise, this function has no effects.
436 * \note This function is not a cancellation point.
438 VLC_API
void vlc_cond_signal(vlc_cond_t
*);
441 * Wakes up all threads waiting on a condition variable.
443 * \note This function is not a cancellation point.
445 VLC_API
void vlc_cond_broadcast(vlc_cond_t
*);
448 * Waits on a condition variable.
450 * The calling thread will be suspended until another thread calls
451 * vlc_cond_signal() or vlc_cond_broadcast() on the same condition variable,
452 * the thread is cancelled with vlc_cancel(), or the system causes a
453 * <em>spurious</em> unsolicited wake-up.
455 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
456 * a recursive mutex. Although it is possible to use the same mutex for
457 * multiple condition, it is not valid to use different mutexes for the same
458 * condition variable at the same time from different threads.
460 * The canonical way to use a condition variable to wait for event foobar is:
462 vlc_mutex_lock(&lock);
463 mutex_cleanup_push(&lock); // release the mutex in case of cancellation
466 vlc_cond_wait(&wait, &lock);
468 // -- foobar is now true, do something about it here --
471 vlc_mutex_unlock(&lock);
474 * \note This function is a cancellation point. In case of thread cancellation,
475 * the mutex is always locked before cancellation proceeds.
477 * \param cond condition variable to wait on
478 * \param mutex mutex which is unlocked while waiting,
479 * then locked again when waking up.
481 VLC_API
void vlc_cond_wait(vlc_cond_t
*cond
, vlc_mutex_t
*mutex
);
484 * Waits on a condition variable up to a certain date.
486 * This works like vlc_cond_wait() but with an additional time-out.
487 * The time-out is expressed as an absolute timestamp using the same arbitrary
488 * time reference as the vlc_tick_now() and vlc_tick_wait() functions.
490 * \note This function is a cancellation point. In case of thread cancellation,
491 * the mutex is always locked before cancellation proceeds.
493 * \param cond condition variable to wait on
494 * \param mutex mutex which is unlocked while waiting,
495 * then locked again when waking up
496 * \param deadline <b>absolute</b> timeout
498 * \return 0 if the condition was signaled, an error code in case of timeout.
500 VLC_API
int vlc_cond_timedwait(vlc_cond_t
*cond
, vlc_mutex_t
*mutex
,
501 vlc_tick_t deadline
);
503 int vlc_cond_timedwait_daytime(vlc_cond_t
*, vlc_mutex_t
*, time_t);
508 * \defgroup semaphore Semaphores
510 * The semaphore is the simplest thread synchronization primitive, consisting
511 * of a simple counter.
513 * See also POSIX @c sem_t .
520 * Storage space for a thread-safe semaphore.
533 * Initializes a semaphore.
535 * @param count initial semaphore value (typically 0)
537 VLC_API
void vlc_sem_init(vlc_sem_t
*, unsigned count
);
540 * Increments the value of a semaphore.
542 * \note This function is not a cancellation point.
544 * \return 0 on success, EOVERFLOW in case of integer overflow.
546 VLC_API
int vlc_sem_post(vlc_sem_t
*);
549 * Waits on a semaphore.
551 * This function atomically waits for the semaphore to become non-zero then
552 * decrements it, and returns. If the semaphore is non-zero on entry, it is
553 * immediately decremented.
555 * \note This function may be a point of cancellation.
557 VLC_API
void vlc_sem_wait(vlc_sem_t
*);
560 * Waits on a semaphore within a deadline.
562 * This function waits for the semaphore just like vlc_sem_wait(), but only
563 * up to a given deadline.
565 * \param sem semaphore to wait for
566 * \param deadline deadline to wait until
568 * \retval 0 the semaphore was decremented
569 * \retval ETIMEDOUT the deadline was reached
571 VLC_API
int vlc_sem_timedwait(vlc_sem_t
*sem
, vlc_tick_t deadline
) VLC_USED
;
576 * \defgroup rwlock Read/write locks
578 * Read/write locks are a type of thread synchronization primitive meant to
579 * protect access to data that is mostly read, and rarely written.
580 * As long as no threads tries to acquire the lock for "writing", any number of
581 * threads can acquire the lock for "reading".
583 * See also POSIX @c pthread_rwlock_t .
588 #ifdef LIBVLC_NEED_RWLOCK
589 typedef struct vlc_rwlock
595 # define VLC_STATIC_RWLOCK { VLC_STATIC_MUTEX, VLC_STATIC_COND, 0 }
599 * Initializes a read/write lock.
601 * After use, a read/write lock must be deinitialized with
602 * vlc_rwlock_destroy().
604 VLC_API
void vlc_rwlock_init(vlc_rwlock_t
*);
607 * Destroys an initialized unused read/write lock.
609 VLC_API
void vlc_rwlock_destroy(vlc_rwlock_t
*);
612 * Acquires a read/write lock for reading.
614 * \note Recursion is allowed.
615 * \note This function may be a point of cancellation.
617 VLC_API
void vlc_rwlock_rdlock(vlc_rwlock_t
*);
620 * Acquires a read/write lock for writing. Recursion is not allowed.
621 * \note This function may be a point of cancellation.
623 VLC_API
void vlc_rwlock_wrlock(vlc_rwlock_t
*);
626 * Releases a read/write lock.
628 * The calling thread must hold the lock. Otherwise behaviour is undefined.
630 * \note This function is not a cancellation point.
632 VLC_API
void vlc_rwlock_unlock(vlc_rwlock_t
*);
637 * Executes a function one time.
639 * The first time this function is called with a given one-time initialization
640 * object, it executes the provided callback.
641 * Any further call with the same object will be a no-op.
643 * In the corner case that the first time execution is ongoing in another
644 * thread, then the function will wait for completion on the other thread
645 * (and then synchronize memory) before it returns.
646 * This ensures that, no matter what, the callback has been executed exactly
647 * once and its side effects are visible after the function returns.
649 * \param once a one-time initialization object
650 * \param cb callback to execute (the first time)
652 VLC_API
void vlc_once(vlc_once_t
*restrict once
, void (*cb
)(void));
655 * \defgroup threadvar Thread-specific variables
659 * Allocates a thread-specific variable.
661 * @param key where to store the thread-specific variable handle
662 * @param destr a destruction callback. It is called whenever a thread exits
663 * and the thread-specific variable has a non-NULL value.
665 * @return 0 on success, a system error code otherwise.
666 * This function can actually fail: on most systems, there is a fixed limit to
667 * the number of thread-specific variables in a given process.
669 VLC_API
int vlc_threadvar_create(vlc_threadvar_t
*key
, void (*destr
) (void *));
672 * Deallocates a thread-specific variable.
674 VLC_API
void vlc_threadvar_delete(vlc_threadvar_t
*);
677 * Sets a thread-specific variable.
679 * \param key thread-local variable key (created with vlc_threadvar_create())
680 * \param value new value for the variable for the calling thread
681 * \return 0 on success, a system error code otherwise.
683 VLC_API
int vlc_threadvar_set(vlc_threadvar_t key
, void *value
);
686 * Gets the value of a thread-local variable for the calling thread.
687 * This function cannot fail.
689 * \return the value associated with the given variable for the calling
690 * or NULL if no value was set.
692 VLC_API
void *vlc_threadvar_get(vlc_threadvar_t
);
697 * Waits on an address.
699 * Puts the calling thread to sleep if a specific unsigned 32-bits value is
700 * stored at a specified address. The thread will sleep until it is woken up by
701 * a call to vlc_atomic_notify_one() or vlc_atomic_notify_all() in another
702 * thread, or spuriously.
704 * If the value does not match, do nothing and return immediately.
706 * \param addr address to check for
707 * \param val value to match at the address
709 void vlc_atomic_wait(void *addr
, unsigned val
);
712 * Waits on an address with a time-out.
714 * This function operates as vlc_atomic_wait() but provides an additional
715 * time-out. If the deadline is reached, the thread resumes and the function
718 * \param addr address to check for
719 * \param val value to match at the address
720 * \param deadline deadline to wait until
722 * \retval 0 the function was woken up before the time-out
723 * \retval ETIMEDOUT the deadline was reached
725 int vlc_atomic_timedwait(void *addr
, unsigned val
, vlc_tick_t deadline
);
727 int vlc_atomic_timedwait_daytime(void *addr
, unsigned val
, time_t deadline
);
730 * Wakes up one thread on an address.
732 * Wakes up (at least) one of the thread sleeping on the specified address.
733 * The address must be equal to the first parameter given by at least one
734 * thread sleeping within the vlc_atomic_wait() or vlc_atomic_timedwait()
735 * functions. If no threads are found, this function does nothing.
737 * \param addr address identifying which threads may be woken up
739 void vlc_atomic_notify_one(void *addr
);
742 * Wakes up all thread on an address.
744 * Wakes up all threads sleeping on the specified address (if any).
745 * Any thread sleeping within a call to vlc_atomic_wait() or
746 * vlc_atomic_timedwait() with the specified address as first call parameter
749 * \param addr address identifying which threads to wake up
751 void vlc_atomic_notify_all(void *addr
);
754 * Creates and starts a new thread.
756 * The thread must be <i>joined</i> with vlc_join() to reclaim resources
757 * when it is not needed anymore.
759 * @param th storage space for the handle of the new thread (cannot be NULL)
761 * @param entry entry point for the thread
762 * @param data data parameter given to the entry point
763 * @param priority thread priority value
764 * @return 0 on success, a standard error code on error.
765 * @note In case of error, the value of *th is undefined.
767 VLC_API
int vlc_clone(vlc_thread_t
*th
, void *(*entry
)(void *), void *data
,
768 int priority
) VLC_USED
;
771 * Marks a thread as cancelled.
773 * Next time the target thread reaches a cancellation point (while not having
774 * disabled cancellation), it will run its cancellation cleanup handler, the
775 * thread variable destructors, and terminate.
777 * vlc_join() must be used regardless of a thread being cancelled or not, to
778 * avoid leaking resources.
780 VLC_API
void vlc_cancel(vlc_thread_t
);
783 * Waits for a thread to complete (if needed), then destroys it.
785 * \note This is a cancellation point. In case of cancellation, the thread is
788 * \warning A thread cannot join itself (normally VLC will abort if this is
789 * attempted). Also a detached thread <b>cannot</b> be joined.
791 * @param th thread handle
792 * @param result [OUT] pointer to write the thread return value or NULL
794 VLC_API
void vlc_join(vlc_thread_t th
, void **result
);
797 * Disables thread cancellation.
799 * This functions saves the current cancellation state (enabled or disabled),
800 * then disables cancellation for the calling thread. It must be called before
801 * entering a piece of code that is not cancellation-safe, unless it can be
802 * proven that the calling thread will not be cancelled.
804 * \note This function is not a cancellation point.
806 * \return Previous cancellation state (opaque value for vlc_restorecancel()).
808 VLC_API
int vlc_savecancel(void);
811 * Restores the cancellation state.
813 * This function restores the cancellation state of the calling thread to
814 * a state previously saved by vlc_savecancel().
816 * \note This function is not a cancellation point.
818 * \param state previous state as returned by vlc_savecancel().
820 VLC_API
void vlc_restorecancel(int state
);
822 typedef struct vlc_cleanup_t vlc_cleanup_t
;
825 * Internal handler for thread cancellation.
827 * Do not call this function directly. Use wrapper macros instead:
828 * vlc_cleanup_push(), vlc_cleanup_pop().
830 VLC_API
void vlc_control_cancel(vlc_cleanup_t
*);
835 * This function returns the identifier of the calling thread. The identifier
836 * cannot change for the entire duration of the thread, and no other thread can
837 * have the same identifier at the same time in the same process. Typically,
838 * the identifier is also unique across all running threads of all existing
839 * processes, but that depends on the operating system.
841 * There are no particular semantics to the thread ID with LibVLC.
842 * It is provided mainly for tracing and debugging.
844 * \warning This function is not currently implemented on all supported
845 * platforms. Where not implemented, it returns (unsigned long)-1.
847 * \return the thread identifier (or -1 if unimplemented)
849 VLC_API
unsigned long vlc_thread_id(void) VLC_USED
;
852 * Precision monotonic clock.
854 * In principles, the clock has a precision of 1 MHz. But the actual resolution
855 * may be much lower, especially when it comes to sleeping with vlc_tick_wait() or
856 * vlc_tick_sleep(). Most general-purpose operating systems provide a resolution of
857 * only 100 to 1000 Hz.
859 * \warning The origin date (time value "zero") is not specified. It is
860 * typically the time the kernel started, but this is platform-dependent.
861 * If you need wall clock time, use gettimeofday() instead.
863 * \return a timestamp in microseconds.
865 VLC_API vlc_tick_t
vlc_tick_now(void);
868 * Waits until a deadline.
870 * \param deadline timestamp to wait for (\ref vlc_tick_now())
872 * \note The deadline may be exceeded due to OS scheduling.
873 * \note This function is a cancellation point.
875 VLC_API
void vlc_tick_wait(vlc_tick_t deadline
);
878 * Waits for an interval of time.
880 * \param delay how long to wait (in microseconds)
882 * \note The delay may be exceeded due to OS scheduling.
883 * \note This function is a cancellation point.
885 VLC_API
void vlc_tick_sleep(vlc_tick_t delay
);
887 #define VLC_HARD_MIN_SLEEP VLC_TICK_FROM_MS(10) /* 10 milliseconds = 1 tick at 100Hz */
888 #define VLC_SOFT_MIN_SLEEP VLC_TICK_FROM_SEC(9) /* 9 seconds */
890 #if defined (__GNUC__) && !defined (__clang__)
891 /* Linux has 100, 250, 300 or 1000Hz
893 * HZ=100 by default on FreeBSD, but some architectures use a 1000Hz timer
897 __attribute__((unused
))
898 __attribute__((noinline
))
899 __attribute__((error("sorry, cannot sleep for such short a time")))
900 vlc_tick_t
impossible_delay( vlc_tick_t delay
)
903 return VLC_HARD_MIN_SLEEP
;
907 __attribute__((unused
))
908 __attribute__((noinline
))
909 __attribute__((warning("use proper event handling instead of short delay")))
910 vlc_tick_t
harmful_delay( vlc_tick_t delay
)
915 # define check_delay( d ) \
916 ((__builtin_constant_p(d < VLC_HARD_MIN_SLEEP) \
917 && (d < VLC_HARD_MIN_SLEEP)) \
918 ? impossible_delay(d) \
919 : ((__builtin_constant_p(d < VLC_SOFT_MIN_SLEEP) \
920 && (d < VLC_SOFT_MIN_SLEEP)) \
925 __attribute__((unused
))
926 __attribute__((noinline
))
927 __attribute__((error("deadlines can not be constant")))
928 vlc_tick_t
impossible_deadline( vlc_tick_t deadline
)
933 # define check_deadline( d ) \
934 (__builtin_constant_p(d) ? impossible_deadline(d) : d)
936 # define check_delay(d) (d)
937 # define check_deadline(d) (d)
940 #define vlc_tick_sleep(d) vlc_tick_sleep(check_delay(d))
941 #define vlc_tick_wait(d) vlc_tick_wait(check_deadline(d))
944 * \defgroup timer Asynchronous/threaded timers
948 * Initializes an asynchronous timer.
950 * \param id pointer to timer to be initialized
951 * \param func function that the timer will call
952 * \param data parameter for the timer function
953 * \return 0 on success, a system error code otherwise.
955 * \warning Asynchronous timers are processed from an unspecified thread.
956 * \note Multiple occurrences of a single interval timer are serialized:
957 * they cannot run concurrently.
959 VLC_API
int vlc_timer_create(vlc_timer_t
*id
, void (*func
)(void *), void *data
)
963 * Destroys an initialized timer.
965 * If needed, the timer is first disarmed. Behaviour is undefined if the
966 * specified timer is not initialized.
968 * \warning This function <b>must</b> be called before the timer data can be
969 * freed and before the timer callback function can be unmapped/unloaded.
971 * \param timer timer to destroy
973 VLC_API
void vlc_timer_destroy(vlc_timer_t timer
);
975 #define VLC_TIMER_DISARM (0)
976 #define VLC_TIMER_FIRE_ONCE (0)
979 * Arms or disarms an initialized timer.
981 * This functions overrides any previous call to itself.
983 * \note A timer can fire later than requested due to system scheduling
984 * limitations. An interval timer can fail to trigger sometimes, either because
985 * the system is busy or suspended, or because a previous iteration of the
986 * timer is still running. See also vlc_timer_getoverrun().
988 * \param timer initialized timer
989 * \param absolute the timer value origin is the same as vlc_tick_now() if true,
990 * the timer value is relative to now if false.
991 * \param value zero to disarm the timer, otherwise the initial time to wait
992 * before firing the timer.
993 * \param interval zero to fire the timer just once, otherwise the timer
994 * repetition interval.
996 VLC_API
void vlc_timer_schedule(vlc_timer_t timer
, bool absolute
,
997 vlc_tick_t value
, vlc_tick_t interval
);
999 static inline void vlc_timer_disarm(vlc_timer_t timer
)
1001 vlc_timer_schedule( timer
, false, VLC_TIMER_DISARM
, 0 );
1004 static inline void vlc_timer_schedule_asap(vlc_timer_t timer
, vlc_tick_t interval
)
1006 vlc_timer_schedule(timer
, false, 1, interval
);
1010 * Fetches and resets the overrun counter for a timer.
1012 * This functions returns the number of times that the interval timer should
1013 * have fired, but the callback was not invoked due to scheduling problems.
1014 * The call resets the counter to zero.
1016 * \param timer initialized timer
1017 * \return the timer overrun counter (typically zero)
1019 VLC_API
unsigned vlc_timer_getoverrun(vlc_timer_t
) VLC_USED
;
1026 * \return number of available (logical) CPUs.
1028 VLC_API
unsigned vlc_GetCPUCount(void);
1030 #if defined (LIBVLC_USE_PTHREAD_CLEANUP)
1032 * Registers a thread cancellation handler.
1034 * This pushes a function to run if the thread is cancelled (or otherwise
1035 * exits prematurely).
1037 * If multiple procedures are registered,
1038 * they are handled in last-in first-out order.
1040 * \note Any call to vlc_cleanup_push() <b>must</b> paired with a call to
1041 * vlc_cleanup_pop().
1042 * \warning Branching into or out of the block between these two function calls
1043 * is not allowed (read: it will likely crash the whole process).
1045 * \param routine procedure to call if the thread ends
1046 * \param arg argument for the procedure
1048 # define vlc_cleanup_push( routine, arg ) pthread_cleanup_push (routine, arg)
1051 * Unregisters the last cancellation handler.
1053 * This pops the cancellation handler that was last pushed with
1054 * vlc_cleanup_push() in the calling thread.
1056 # define vlc_cleanup_pop( ) pthread_cleanup_pop (0)
1058 #else /* !LIBVLC_USE_PTHREAD_CLEANUP */
1059 struct vlc_cleanup_t
1061 vlc_cleanup_t
*next
;
1062 void (*proc
) (void *);
1066 # ifndef __cplusplus
1067 /* This macros opens a code block on purpose: It reduces the chance of
1068 * not pairing the push and pop. It also matches the POSIX Thread internals.
1069 * That way, Win32 developers will not accidentally break other platforms.
1071 # define vlc_cleanup_push( routine, arg ) \
1073 vlc_control_cancel(&(vlc_cleanup_t){ NULL, routine, arg })
1075 # define vlc_cleanup_pop( ) \
1076 vlc_control_cancel (NULL); \
1079 # define vlc_cleanup_push(routine, arg) \
1080 static_assert(false, "don't use vlc_cleanup_push in portable C++ code")
1081 # define vlc_cleanup_pop() \
1082 static_assert(false, "don't use vlc_cleanup_pop in portable C++ code")
1085 #endif /* !LIBVLC_USE_PTHREAD_CLEANUP */
1087 static inline void vlc_cleanup_lock (void *lock
)
1089 vlc_mutex_unlock ((vlc_mutex_t
*)lock
);
1091 #define mutex_cleanup_push( lock ) vlc_cleanup_push (vlc_cleanup_lock, lock)
1094 void vlc_cancel_addr_set(atomic_uint
*addr
);
1095 void vlc_cancel_addr_clear(atomic_uint
*addr
);
1098 * Helper C++ class to lock a mutex.
1100 * The mutex is locked when the object is created, and unlocked when the object
1103 class vlc_mutex_locker
1108 vlc_mutex_locker (vlc_mutex_t
*m
) : lock (m
)
1110 vlc_mutex_lock (lock
);
1113 ~vlc_mutex_locker (void)
1115 vlc_mutex_unlock (lock
);
1123 VLC_AVCODEC_MUTEX
= 0,
1130 /* Insert new entry HERE */
1135 * Internal handler for global mutexes.
1137 * Do not use this function directly. Use helper macros instead:
1138 * vlc_global_lock(), vlc_global_unlock().
1140 VLC_API
void vlc_global_mutex(unsigned, bool);
1143 * Acquires a global mutex.
1145 #define vlc_global_lock( n ) vlc_global_mutex(n, true)
1148 * Releases a global mutex.
1150 #define vlc_global_unlock( n ) vlc_global_mutex(n, false)
1154 #endif /* !_VLC_THREADS_H */