VLC  4.0.0-dev
vlc_threads.h
Go to the documentation of this file.
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
7  *
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>
12  *
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.
17  *
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.
22  *
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  *****************************************************************************/
27 
28 #ifndef VLC_THREADS_H_
29 #define VLC_THREADS_H_
30 
31 #ifndef __cplusplus
32 #include <stdatomic.h>
33 #endif
34 
35 /**
36  * \ingroup os
37  * \defgroup thread Threads and synchronization primitives
38  * @{
39  * \file
40  * Thread primitive declarations
41  */
42 
43 /**
44  * Issues an explicit deferred cancellation point.
45  *
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).
50  */
51 VLC_API void vlc_testcancel(void);
52 
53 #if defined (_WIN32)
54 # include <process.h>
55 # ifndef ETIMEDOUT
56 # define ETIMEDOUT 10060 /* This is the value in winsock.h. */
57 # endif
58 
59 typedef struct vlc_thread *vlc_thread_t;
60 # define VLC_THREAD_CANCELED NULL
61 
62 # define LIBVLC_NEED_SLEEP
63 typedef struct vlc_threadvar *vlc_threadvar_t;
64 typedef struct vlc_timer *vlc_timer_t;
65 
66 # define VLC_THREAD_PRIORITY_LOW 0
67 # define VLC_THREAD_PRIORITY_INPUT THREAD_PRIORITY_ABOVE_NORMAL
68 # define VLC_THREAD_PRIORITY_AUDIO THREAD_PRIORITY_HIGHEST
69 # define VLC_THREAD_PRIORITY_VIDEO 0
70 # define VLC_THREAD_PRIORITY_OUTPUT THREAD_PRIORITY_ABOVE_NORMAL
71 # define VLC_THREAD_PRIORITY_HIGHEST THREAD_PRIORITY_TIME_CRITICAL
72 
73 static inline int vlc_poll(struct pollfd *fds, unsigned nfds, int timeout)
74 {
75  int val;
76 
78  val = poll(fds, nfds, timeout);
79  if (val < 0)
81  return val;
82 }
83 # define poll(u,n,t) vlc_poll(u, n, t)
84 
85 #elif defined (__OS2__)
86 # include <errno.h>
87 
88 typedef struct vlc_thread *vlc_thread_t;
89 #define VLC_THREAD_CANCELED NULL
90 
91 typedef struct vlc_threadvar *vlc_threadvar_t;
92 typedef struct vlc_timer *vlc_timer_t;
93 
94 # define VLC_THREAD_PRIORITY_LOW 0
95 # define VLC_THREAD_PRIORITY_INPUT 1
96 # define VLC_THREAD_PRIORITY_AUDIO VLC_THREAD_PRIORITY_HIGHEST
97 # define VLC_THREAD_PRIORITY_VIDEO 0
98 # define VLC_THREAD_PRIORITY_OUTPUT 1
99 # define VLC_THREAD_PRIORITY_HIGHEST 2
100 
101 # define pthread_sigmask sigprocmask
102 
103 static inline int vlc_poll (struct pollfd *fds, unsigned nfds, int timeout)
104 {
105  static int (*vlc_poll_os2)(struct pollfd *, unsigned, int) = NULL;
106 
107  if (!vlc_poll_os2)
108  {
109  HMODULE hmod;
110  CHAR szFailed[CCHMAXPATH];
111 
112  if (DosLoadModule(szFailed, sizeof(szFailed), "vlccore", &hmod))
113  return -1;
114 
115  if (DosQueryProcAddr(hmod, 0, "_vlc_poll_os2", (PFN *)&vlc_poll_os2))
116  return -1;
117  }
118 
119  return (*vlc_poll_os2)(fds, nfds, timeout);
120 }
121 # define poll(u,n,t) vlc_poll(u, n, t)
122 
123 #elif defined (__ANDROID__) /* pthreads subset without pthread_cancel() */
124 # include <unistd.h>
125 # include <pthread.h>
126 # include <poll.h>
127 # define LIBVLC_USE_PTHREAD_CLEANUP 1
128 # define LIBVLC_NEED_SLEEP
129 
130 typedef struct vlc_thread *vlc_thread_t;
131 #define VLC_THREAD_CANCELED NULL
132 typedef pthread_key_t vlc_threadvar_t;
133 typedef struct vlc_timer *vlc_timer_t;
134 
135 # define VLC_THREAD_PRIORITY_LOW 0
136 # define VLC_THREAD_PRIORITY_INPUT 0
137 # define VLC_THREAD_PRIORITY_AUDIO 0
138 # define VLC_THREAD_PRIORITY_VIDEO 0
139 # define VLC_THREAD_PRIORITY_OUTPUT 0
140 # define VLC_THREAD_PRIORITY_HIGHEST 0
141 
142 static inline int vlc_poll (struct pollfd *fds, unsigned nfds, int timeout)
143 {
144  int val;
145 
146  do
147  {
148  int ugly_timeout = ((unsigned)timeout >= 50) ? 50 : timeout;
149  if (timeout >= 0)
150  timeout -= ugly_timeout;
151 
152  vlc_testcancel ();
153  val = poll (fds, nfds, ugly_timeout);
154  }
155  while (val == 0 && timeout != 0);
156 
157  return val;
158 }
159 
160 # define poll(u,n,t) vlc_poll(u, n, t)
161 
162 #else /* POSIX threads */
163 # include <unistd.h> /* _POSIX_SPIN_LOCKS */
164 # include <pthread.h>
165 
166 /**
167  * Whether LibVLC threads are based on POSIX threads.
168  */
169 # define LIBVLC_USE_PTHREAD 1
170 
171 /**
172  * Whether LibVLC thread cancellation is based on POSIX threads.
173  */
174 # define LIBVLC_USE_PTHREAD_CLEANUP 1
175 
176 /**
177  * Thread handle.
178  */
179 typedef struct
180 {
181  pthread_t handle;
183 
184 /**
185  * Return value of a canceled thread.
186  */
187 #define VLC_THREAD_CANCELED PTHREAD_CANCELED
188 
189 /**
190  * Thread-local key handle.
191  *
192  * \ingroup threadvar
193  */
194 typedef pthread_key_t vlc_threadvar_t;
195 
196 /**
197  * Threaded timer handle.
198  *
199  * \ingroup timer
200  */
201 typedef struct vlc_timer *vlc_timer_t;
202 
203 /* Thread priorities.
204  * No effect for POSIX threads
205  */
206 # define VLC_THREAD_PRIORITY_LOW 0
207 # define VLC_THREAD_PRIORITY_INPUT 0
208 # define VLC_THREAD_PRIORITY_AUDIO 0
209 # define VLC_THREAD_PRIORITY_VIDEO 0
210 # define VLC_THREAD_PRIORITY_OUTPUT 0
211 # define VLC_THREAD_PRIORITY_HIGHEST 0
212 
213 #endif
214 
215 /**
216  * \defgroup mutex Mutual exclusion locks
217  * @{
218  */
219 /**
220  * Mutex.
221  *
222  * Storage space for a mutual exclusion lock.
223  */
224 typedef struct
225 {
226  union {
227 #ifndef __cplusplus
228  struct {
229  atomic_uint value;
230  atomic_uint recursion;
231  _Atomic (const void *) owner;
232  };
233 #endif
234  struct {
235  unsigned int value;
236  unsigned int recursion;
237  const void *owner;
238  } dummy;
239  };
240 } vlc_mutex_t;
241 
242 /**
243  * Static initializer for (static) mutex.
244  *
245  * \note This only works in C code.
246  * In C++, consider using a global \ref vlc::threads::mutex instance instead.
247  */
248 #define VLC_STATIC_MUTEX { \
249  .value = ATOMIC_VAR_INIT(0), \
250  .recursion = ATOMIC_VAR_INIT(0), \
251  .owner = ATOMIC_VAR_INIT(NULL), \
252 }
253 
254 /**
255  * Initializes a fast mutex.
256  *
257  * Recursive locking of a fast mutex is undefined behaviour. (In debug builds,
258  * recursive locking will cause an assertion failure.)
259  */
261 
262 /**
263  * Initializes a recursive mutex.
264  * \warning This is strongly discouraged. Please use normal mutexes.
265  */
267 
268 /**
269  * Acquires a mutex.
270  *
271  * If needed, this waits for any other thread to release it.
272  *
273  * \warning Beware of deadlocks when locking multiple mutexes at the same time,
274  * or when using mutexes from callbacks.
275  *
276  * \note This function is not a cancellation point.
277  */
279 
280 /**
281  * Tries to acquire a mutex.
282  *
283  * This function acquires the mutex if and only if it is not currently held by
284  * another thread. This function never sleeps and can be used in delay-critical
285  * code paths.
286  *
287  * \note This function is not a cancellation point.
288  *
289  * \warning If this function fails, then the mutex is held... by another
290  * thread. The calling thread must deal with the error appropriately. That
291  * typically implies postponing the operations that would have required the
292  * mutex. If the thread cannot defer those operations, then it must use
293  * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
294  *
295  * @return 0 if the mutex could be acquired, an error code otherwise.
296  */
298 
299 /**
300  * Releases a mutex.
301  *
302  * If the mutex is not held by the calling thread, the behaviour is undefined.
303  *
304  * \note This function is not a cancellation point.
305  */
307 
308 /**
309  * Checks if a mutex is locked.
310  *
311  * Do not use this function directly. Use vlc_mutex_assert() instead.
312  *
313  * @note
314  * This function has no effects.
315  * It is only meant to be use in run-time assertions.
316  *
317  * @warning This function might not return correct results in non-debug builds.
318  *
319  * @retval false the mutex is not locked by the calling thread
320  * @retval true the mutex is locked by the calling thread
321  */
323 
324 /**
325  * Asserts that a mutex is locked by the calling thread.
326  */
327 #define vlc_mutex_assert(m) assert(vlc_mutex_held(m))
328 
329 /** @} */
330 
331 /**
332  * \defgroup condvar Condition variables
333  *
334  * The condition variable is the most common and generic mean for threads to
335  * wait for events triggered by other threads.
336  *
337  * See also POSIX @c pthread_cond_t .
338  * @{
339  */
340 
341 struct vlc_cond_waiter;
342 
343 /**
344  * Condition variable.
345  *
346  * Storage space for a thread condition variable.
347  */
348 typedef struct
349 {
350  struct vlc_cond_waiter *head;
353 
354 /**
355  * Static initializer for (static) condition variable.
356  */
357 #define VLC_STATIC_COND { NULL, VLC_STATIC_MUTEX }
358 
359 /**
360  * Initializes a condition variable.
361  */
363 
364 /**
365  * Wakes up one thread waiting on a condition variable.
366  *
367  * If any thread is currently waiting on the condition variable, at least one
368  * of those threads will be woken up. Otherwise, this function has no effects.
369  *
370  * \note This function is not a cancellation point.
371  */
373 
374 /**
375  * Wakes up all threads waiting on a condition variable.
376  *
377  * \note This function is not a cancellation point.
378  */
380 
381 /**
382  * Waits on a condition variable.
383  *
384  * The calling thread will be suspended until another thread calls
385  * vlc_cond_signal() or vlc_cond_broadcast() on the same condition variable,
386  * the thread is cancelled with vlc_cancel(), or the system causes a
387  * <em>spurious</em> unsolicited wake-up.
388  *
389  * A mutex is needed to wait on a condition variable. It must <b>not</b> be
390  * a recursive mutex. Although it is possible to use the same mutex for
391  * multiple condition, it is not valid to use different mutexes for the same
392  * condition variable at the same time from different threads.
393  *
394  * The canonical way to use a condition variable to wait for event foobar is:
395  @code
396  vlc_mutex_lock(&lock);
397 
398  while (!foobar)
399  vlc_cond_wait(&wait, &lock);
400 
401  // -- foobar is now true, do something about it here --
402 
403  vlc_mutex_unlock(&lock);
404  @endcode
405  *
406  * \param cond condition variable to wait on
407  * \param mutex mutex which is unlocked while waiting,
408  * then locked again when waking up.
409  */
410 VLC_API void vlc_cond_wait(vlc_cond_t *cond, vlc_mutex_t *mutex);
411 
412 /**
413  * Waits on a condition variable up to a certain date.
414  *
415  * This works like vlc_cond_wait() but with an additional time-out.
416  * The time-out is expressed as an absolute timestamp using the same arbitrary
417  * time reference as the vlc_tick_now() and vlc_tick_wait() functions.
418  *
419  * \param cond condition variable to wait on
420  * \param mutex mutex which is unlocked while waiting,
421  * then locked again when waking up
422  * \param deadline <b>absolute</b> timeout
423  *
424  * \return 0 if the condition was signaled, an error code in case of timeout.
425  */
427  vlc_tick_t deadline);
428 
430 
431 /** @} */
432 
433 /**
434  * \defgroup semaphore Semaphores
435  *
436  * The semaphore is the simplest thread synchronization primitive, consisting
437  * of a simple counter.
438  *
439  * See also POSIX @c sem_t .
440  *
441  * @{
442  */
443 /**
444  * Semaphore.
445  *
446  * Storage space for a thread-safe semaphore.
447  */
448 typedef struct
449 {
450  union {
451 #ifndef __cplusplus
452  atomic_uint value;
453 #endif
454  int dummy;
455  };
456 } vlc_sem_t;
457 
458 /**
459  * Initializes a semaphore.
460  *
461  * @param count initial semaphore value (typically 0)
462  */
463 VLC_API void vlc_sem_init(vlc_sem_t *, unsigned count);
464 
465 /**
466  * Increments the value of a semaphore.
467  *
468  * \note This function is not a cancellation point.
469  *
470  * \return 0 on success, EOVERFLOW in case of integer overflow.
471  */
473 
474 /**
475  * Waits on a semaphore.
476  *
477  * This function atomically waits for the semaphore to become non-zero then
478  * decrements it, and returns. If the semaphore is non-zero on entry, it is
479  * immediately decremented.
480  *
481  * \note This function may be a point of cancellation.
482  */
484 
485 /**
486  * Tries to decrement a semaphore.
487  *
488  * This function decrements the semaphore if its value is not zero.
489  *
490  * \param sem semaphore to decrement
491  *
492  * \retval 0 the semaphore was decremented
493  * \retval EAGAIN the semaphore was zero and could not be decremented
494  */
496 
497 /**
498  * Waits on a semaphore within a deadline.
499  *
500  * This function waits for the semaphore just like vlc_sem_wait(), but only
501  * up to a given deadline.
502  *
503  * \param sem semaphore to wait for
504  * \param deadline deadline to wait until
505  *
506  * \retval 0 the semaphore was decremented
507  * \retval ETIMEDOUT the deadline was reached
508  */
510 
511 /** @} */
512 
513 /**
514  * \defgroup rwlock Read/write locks
515  *
516  * Read/write locks are a type of thread synchronization primitive meant to
517  * protect access to data that is mostly read, and rarely written.
518  * As long as no threads tries to acquire the lock for "writing", any number of
519  * threads can acquire the lock for "reading".
520  *
521  * See also POSIX @c pthread_rwlock_t .
522  *
523  * @{
524  */
525 
526 /**
527  * Read/write lock.
528  *
529  * Storage space for a slim reader/writer lock.
530  */
531 typedef struct vlc_rwlock
532 {
535  long state;
537 
538 /**
539  * Static initializer for (static) read/write lock.
540  */
541 #define VLC_STATIC_RWLOCK { VLC_STATIC_MUTEX, VLC_STATIC_COND, 0 }
542 
543 /**
544  * Initializes a read/write lock.
545  */
547 
548 /**
549  * Acquires a read/write lock for reading.
550  *
551  * \note Recursion is allowed.
552  */
554 
555 /**
556  * Acquires a read/write lock for writing. Recursion is not allowed.
557  */
559 
560 /**
561  * Releases a read/write lock.
562  *
563  * The calling thread must hold the lock. Otherwise behaviour is undefined.
564  *
565  * \note This function is not a cancellation point.
566  */
568 
569 /** @} */
570 
571 #ifndef __cplusplus
572 /**
573  * One-time initialization.
574  *
575  * A one-time initialization object must always be initialized assigned to
576  * \ref VLC_STATIC_ONCE before use.
577  */
578 typedef struct
579 {
580  atomic_uint value;
582 
583 /**
584  * Static initializer for one-time initialization.
585  */
586 #define VLC_STATIC_ONCE { ATOMIC_VAR_INIT(0) }
587 
588 /**
589  * Executes a function one time.
590  *
591  * The first time this function is called with a given one-time initialization
592  * object, it executes the provided callback.
593  * Any further call with the same object will be a no-op.
594  *
595  * In the corner case that the first time execution is ongoing in another
596  * thread, then the function will wait for completion on the other thread
597  * (and then synchronize memory) before it returns.
598  * This ensures that, no matter what, the callback has been executed exactly
599  * once and its side effects are visible after the function returns.
600  *
601  * \param once a one-time initialization object
602  * \param cb callback to execute (the first time)
603  */
604 VLC_API void vlc_once(vlc_once_t *restrict once, void (*cb)(void));
605 
606 static inline void vlc_once_inline(vlc_once_t *restrict once, void (*cb)(void))
607 {
608  /* Fast path: check if already initialized */
609  if (unlikely(atomic_load_explicit(&once->value, memory_order_acquire) < 3))
610  vlc_once(once, cb);
611 }
612 #define vlc_once(once, cb) vlc_once_inline(once, cb)
613 #endif
614 
615 /**
616  * \defgroup threadvar Thread-specific variables
617  * @{
618  */
619 /**
620  * Allocates a thread-specific variable.
621  *
622  * @param key where to store the thread-specific variable handle
623  * @param destr a destruction callback. It is called whenever a thread exits
624  * and the thread-specific variable has a non-NULL value.
625  *
626  * @return 0 on success, a system error code otherwise.
627  * This function can actually fail: on most systems, there is a fixed limit to
628  * the number of thread-specific variables in a given process.
629  */
630 VLC_API int vlc_threadvar_create(vlc_threadvar_t *key, void (*destr) (void *));
631 
632 /**
633  * Deallocates a thread-specific variable.
634  */
636 
637 /**
638  * Sets a thread-specific variable.
639 
640  * \param key thread-local variable key (created with vlc_threadvar_create())
641  * \param value new value for the variable for the calling thread
642  * \return 0 on success, a system error code otherwise.
643  */
644 VLC_API int vlc_threadvar_set(vlc_threadvar_t key, void *value);
645 
646 /**
647  * Gets the value of a thread-local variable for the calling thread.
648  * This function cannot fail.
649  *
650  * \return the value associated with the given variable for the calling
651  * or NULL if no value was set.
652  */
654 
655 /** @} */
656 
657 /**
658  * Waits on an address.
659  *
660  * Puts the calling thread to sleep if a specific unsigned 32-bits value is
661  * stored at a specified address. The thread will sleep until it is woken up by
662  * a call to vlc_atomic_notify_one() or vlc_atomic_notify_all() in another
663  * thread, or spuriously.
664  *
665  * If the value does not match, do nothing and return immediately.
666  *
667  * \param addr address to check for
668  * \param val value to match at the address
669  */
670 void vlc_atomic_wait(void *addr, unsigned val);
671 
672 /**
673  * Waits on an address with a time-out.
674  *
675  * This function operates as vlc_atomic_wait() but provides an additional
676  * time-out. If the deadline is reached, the thread resumes and the function
677  * returns.
678  *
679  * \param addr address to check for
680  * \param val value to match at the address
681  * \param deadline deadline to wait until
682  *
683  * \retval 0 the function was woken up before the time-out
684  * \retval ETIMEDOUT the deadline was reached
685  */
686 int vlc_atomic_timedwait(void *addr, unsigned val, vlc_tick_t deadline);
687 
688 int vlc_atomic_timedwait_daytime(void *addr, unsigned val, time_t deadline);
689 
690 /**
691  * Wakes up one thread on an address.
692  *
693  * Wakes up (at least) one of the thread sleeping on the specified address.
694  * The address must be equal to the first parameter given by at least one
695  * thread sleeping within the vlc_atomic_wait() or vlc_atomic_timedwait()
696  * functions. If no threads are found, this function does nothing.
697  *
698  * \param addr address identifying which threads may be woken up
699  */
700 void vlc_atomic_notify_one(void *addr);
701 
702 /**
703  * Wakes up all thread on an address.
704  *
705  * Wakes up all threads sleeping on the specified address (if any).
706  * Any thread sleeping within a call to vlc_atomic_wait() or
707  * vlc_atomic_timedwait() with the specified address as first call parameter
708  * will be woken up.
709  *
710  * \param addr address identifying which threads to wake up
711  */
712 void vlc_atomic_notify_all(void *addr);
713 
714 /**
715  * Creates and starts a new thread.
716  *
717  * The thread must be <i>joined</i> with vlc_join() to reclaim resources
718  * when it is not needed anymore.
719  *
720  * @param th storage space for the handle of the new thread (cannot be NULL)
721  * [OUT]
722  * @param entry entry point for the thread
723  * @param data data parameter given to the entry point
724  * @param priority thread priority value
725  * @return 0 on success, a standard error code on error.
726  * @note In case of error, the value of *th is undefined.
727  */
728 VLC_API int vlc_clone(vlc_thread_t *th, void *(*entry)(void *), void *data,
729  int priority) VLC_USED;
730 
731 /**
732  * Marks a thread as cancelled.
733  *
734  * Next time the target thread reaches a cancellation point (while not having
735  * disabled cancellation), it will run its cancellation cleanup handler, the
736  * thread variable destructors, and terminate.
737  *
738  * vlc_join() must be used regardless of a thread being cancelled or not, to
739  * avoid leaking resources.
740  */
742 
743 /**
744  * Waits for a thread to complete (if needed), then destroys it.
745  *
746  * \note This is a cancellation point. In case of cancellation, the thread is
747  * <b>not</b> joined.
748 
749  * \warning A thread cannot join itself (normally VLC will abort if this is
750  * attempted). Also a detached thread <b>cannot</b> be joined.
751  *
752  * @param th thread handle
753  * @param result [OUT] pointer to write the thread return value or NULL
754  */
755 VLC_API void vlc_join(vlc_thread_t th, void **result);
756 
757 /**
758  * Disables thread cancellation.
759  *
760  * This functions saves the current cancellation state (enabled or disabled),
761  * then disables cancellation for the calling thread. It must be called before
762  * entering a piece of code that is not cancellation-safe, unless it can be
763  * proven that the calling thread will not be cancelled.
764  *
765  * \note This function is not a cancellation point.
766  *
767  * \return Previous cancellation state (opaque value for vlc_restorecancel()).
768  */
769 VLC_API int vlc_savecancel(void);
770 
771 /**
772  * Restores the cancellation state.
773  *
774  * This function restores the cancellation state of the calling thread to
775  * a state previously saved by vlc_savecancel().
776  *
777  * \note This function is not a cancellation point.
778  *
779  * \param state previous state as returned by vlc_savecancel().
780  */
782 
783 typedef struct vlc_cleanup_t vlc_cleanup_t;
784 
785 /**
786  * Internal handler for thread cancellation.
787  *
788  * Do not call this function directly. Use wrapper macros instead:
789  * vlc_cleanup_push(), vlc_cleanup_pop().
790  */
792 
793 /**
794  * Thread identifier.
795  *
796  * This function returns the identifier of the calling thread. The identifier
797  * cannot change for the entire duration of the thread, and no other thread can
798  * have the same identifier at the same time in the same process. Typically,
799  * the identifier is also unique across all running threads of all existing
800  * processes, but that depends on the operating system.
801  *
802  * There are no particular semantics to the thread ID with LibVLC.
803  * It is provided mainly for tracing and debugging.
804  *
805  * \warning This function is not currently implemented on all supported
806  * platforms. Where not implemented, it returns (unsigned long)-1.
807  *
808  * \return the thread identifier (or -1 if unimplemented)
809  */
810 VLC_API unsigned long vlc_thread_id(void) VLC_USED;
811 
812 /**
813  * Precision monotonic clock.
814  *
815  * In principles, the clock has a precision of 1 MHz. But the actual resolution
816  * may be much lower, especially when it comes to sleeping with vlc_tick_wait() or
817  * vlc_tick_sleep(). Most general-purpose operating systems provide a resolution of
818  * only 100 to 1000 Hz.
819  *
820  * \warning The origin date (time value "zero") is not specified. It is
821  * typically the time the kernel started, but this is platform-dependent.
822  * If you need wall clock time, use gettimeofday() instead.
823  *
824  * \return a timestamp in microseconds.
825  */
827 
828 /**
829  * Waits until a deadline.
830  *
831  * \param deadline timestamp to wait for (\ref vlc_tick_now())
832  *
833  * \note The deadline may be exceeded due to OS scheduling.
834  * \note This function is a cancellation point.
835  */
836 VLC_API void vlc_tick_wait(vlc_tick_t deadline);
837 
838 /**
839  * Waits for an interval of time.
840  *
841  * \param delay how long to wait (in microseconds)
842  *
843  * \note The delay may be exceeded due to OS scheduling.
844  * \note This function is a cancellation point.
845  */
846 VLC_API void vlc_tick_sleep(vlc_tick_t delay);
847 
848 #define VLC_HARD_MIN_SLEEP VLC_TICK_FROM_MS(10) /* 10 milliseconds = 1 tick at 100Hz */
849 #define VLC_SOFT_MIN_SLEEP VLC_TICK_FROM_SEC(9) /* 9 seconds */
850 
851 #if defined (__GNUC__) && !defined (__clang__)
852 /* Linux has 100, 250, 300 or 1000Hz
853  *
854  * HZ=100 by default on FreeBSD, but some architectures use a 1000Hz timer
855  */
856 
857 static
858 __attribute__((unused))
859 __attribute__((noinline))
860 __attribute__((error("sorry, cannot sleep for such short a time")))
861 vlc_tick_t impossible_delay( vlc_tick_t delay )
862 {
863  (void) delay;
864  return VLC_HARD_MIN_SLEEP;
865 }
866 
867 static
868 __attribute__((unused))
869 __attribute__((noinline))
870 __attribute__((warning("use proper event handling instead of short delay")))
871 vlc_tick_t harmful_delay( vlc_tick_t delay )
872 {
873  return delay;
874 }
875 
876 # define check_delay( d ) \
877  ((__builtin_constant_p(d < VLC_HARD_MIN_SLEEP) \
878  && (d < VLC_HARD_MIN_SLEEP)) \
879  ? impossible_delay(d) \
880  : ((__builtin_constant_p(d < VLC_SOFT_MIN_SLEEP) \
881  && (d < VLC_SOFT_MIN_SLEEP)) \
882  ? harmful_delay(d) \
883  : d))
884 
885 static
886 __attribute__((unused))
887 __attribute__((noinline))
888 __attribute__((error("deadlines can not be constant")))
889 vlc_tick_t impossible_deadline( vlc_tick_t deadline )
890 {
891  return deadline;
892 }
893 
894 # define check_deadline( d ) \
895  (__builtin_constant_p(d) ? impossible_deadline(d) : d)
896 #else
897 # define check_delay(d) (d)
898 # define check_deadline(d) (d)
899 #endif
900 
901 #define vlc_tick_sleep(d) vlc_tick_sleep(check_delay(d))
902 #define vlc_tick_wait(d) vlc_tick_wait(check_deadline(d))
903 
904 /**
905  * \defgroup timer Asynchronous/threaded timers
906  * @{
907  */
908 /**
909  * Initializes an asynchronous timer.
910  *
911  * \param id pointer to timer to be initialized
912  * \param func function that the timer will call
913  * \param data parameter for the timer function
914  * \return 0 on success, a system error code otherwise.
915  *
916  * \warning Asynchronous timers are processed from an unspecified thread.
917  * \note Multiple occurrences of a single interval timer are serialized:
918  * they cannot run concurrently.
919  */
920 VLC_API int vlc_timer_create(vlc_timer_t *id, void (*func)(void *), void *data)
921 VLC_USED;
922 
923 /**
924  * Destroys an initialized timer.
925  *
926  * If needed, the timer is first disarmed. Behaviour is undefined if the
927  * specified timer is not initialized.
928  *
929  * \warning This function <b>must</b> be called before the timer data can be
930  * freed and before the timer callback function can be unmapped/unloaded.
931  *
932  * \param timer timer to destroy
933  */
935 
936 #define VLC_TIMER_DISARM (0)
937 #define VLC_TIMER_FIRE_ONCE (0)
938 
939 /**
940  * Arms or disarms an initialized timer.
941  *
942  * This functions overrides any previous call to itself.
943  *
944  * \note A timer can fire later than requested due to system scheduling
945  * limitations. An interval timer can fail to trigger sometimes, either because
946  * the system is busy or suspended, or because a previous iteration of the
947  * timer is still running. See also vlc_timer_getoverrun().
948  *
949  * \param timer initialized timer
950  * \param absolute the timer value origin is the same as vlc_tick_now() if true,
951  * the timer value is relative to now if false.
952  * \param value zero to disarm the timer, otherwise the initial time to wait
953  * before firing the timer.
954  * \param interval zero to fire the timer just once, otherwise the timer
955  * repetition interval.
956  */
957 VLC_API void vlc_timer_schedule(vlc_timer_t timer, bool absolute,
958  vlc_tick_t value, vlc_tick_t interval);
959 
960 static inline void vlc_timer_disarm(vlc_timer_t timer)
961 {
962  vlc_timer_schedule( timer, false, VLC_TIMER_DISARM, 0 );
963 }
964 
965 static inline void vlc_timer_schedule_asap(vlc_timer_t timer, vlc_tick_t interval)
966 {
967  vlc_timer_schedule(timer, false, 1, interval);
968 }
969 
970 /**
971  * Fetches and resets the overrun counter for a timer.
972  *
973  * This functions returns the number of times that the interval timer should
974  * have fired, but the callback was not invoked due to scheduling problems.
975  * The call resets the counter to zero.
976  *
977  * \param timer initialized timer
978  * \return the timer overrun counter (typically zero)
979  */
981 
982 /** @} */
983 
984 /**
985  * Count CPUs.
986  *
987  * \return number of available (logical) CPUs.
988  */
989 VLC_API unsigned vlc_GetCPUCount(void);
990 
991 #if defined (LIBVLC_USE_PTHREAD_CLEANUP)
992 /**
993  * Registers a thread cancellation handler.
994  *
995  * This pushes a function to run if the thread is cancelled (or otherwise
996  * exits prematurely).
997  *
998  * If multiple procedures are registered,
999  * they are handled in last-in first-out order.
1000  *
1001  * \note Any call to vlc_cleanup_push() <b>must</b> paired with a call to
1002  * vlc_cleanup_pop().
1003  * \warning Branching into or out of the block between these two function calls
1004  * is not allowed (read: it will likely crash the whole process).
1005  *
1006  * \param routine procedure to call if the thread ends
1007  * \param arg argument for the procedure
1008  */
1009 # define vlc_cleanup_push( routine, arg ) pthread_cleanup_push (routine, arg)
1011 /**
1012  * Unregisters the last cancellation handler.
1013  *
1014  * This pops the cancellation handler that was last pushed with
1015  * vlc_cleanup_push() in the calling thread.
1016  */
1017 # define vlc_cleanup_pop( ) pthread_cleanup_pop (0)
1019 #else /* !LIBVLC_USE_PTHREAD_CLEANUP */
1020 struct vlc_cleanup_t
1021 {
1022  vlc_cleanup_t *next;
1023  void (*proc) (void *);
1024  void *data;
1025 };
1026 
1027 # ifndef __cplusplus
1028 /* This macros opens a code block on purpose: It reduces the chance of
1029  * not pairing the push and pop. It also matches the POSIX Thread internals.
1030  * That way, Win32 developers will not accidentally break other platforms.
1031  */
1032 # define vlc_cleanup_push( routine, arg ) \
1033  do { \
1034  vlc_control_cancel(&(vlc_cleanup_t){ NULL, routine, arg })
1035 
1036 # define vlc_cleanup_pop( ) \
1037  vlc_control_cancel (NULL); \
1038  } while (0)
1039 # else
1040 # define vlc_cleanup_push(routine, arg) \
1041  static_assert(false, "don't use vlc_cleanup_push in portable C++ code")
1042 # define vlc_cleanup_pop() \
1043  static_assert(false, "don't use vlc_cleanup_pop in portable C++ code")
1044 # endif
1045 
1046 #endif /* !LIBVLC_USE_PTHREAD_CLEANUP */
1047 
1048 static inline void vlc_cleanup_lock (void *lock)
1051 }
1052 #define mutex_cleanup_push( lock ) vlc_cleanup_push (vlc_cleanup_lock, lock)
1054 #ifndef __cplusplus
1055 void vlc_cancel_addr_set(atomic_uint *addr);
1056 void vlc_cancel_addr_clear(atomic_uint *addr);
1057 #else
1058 /**
1059  * Helper C++ class to lock a mutex.
1060  *
1061  * The mutex is locked when the object is created, and unlocked when the object
1062  * is destroyed.
1063  */
1064 class vlc_mutex_locker
1065 {
1066  private:
1067  vlc_mutex_t *lock;
1068  public:
1069  vlc_mutex_locker (vlc_mutex_t *m) : lock (m)
1070  {
1071  vlc_mutex_lock (lock);
1072  }
1073 
1074  ~vlc_mutex_locker (void)
1075  {
1077  }
1078 };
1079 
1080 #endif
1081 
1082 enum
1083 {
1084  VLC_AVCODEC_MUTEX = 0,
1088 #ifdef _WIN32
1089  VLC_MTA_MUTEX,
1090 #endif
1091  /* Insert new entry HERE */
1093 };
1094 
1095 /**
1096  * Internal handler for global mutexes.
1097  *
1098  * Do not use this function directly. Use helper macros instead:
1099  * vlc_global_lock(), vlc_global_unlock().
1100  */
1101 VLC_API void vlc_global_mutex(unsigned, bool);
1102 
1103 /**
1104  * Acquires a global mutex.
1105  */
1106 #define vlc_global_lock( n ) vlc_global_mutex(n, true)
1108 /**
1109  * Releases a global mutex.
1110  */
1111 #define vlc_global_unlock( n ) vlc_global_mutex(n, false)
1113 /** @} */
1114 
1115 #endif /* !_VLC_THREADS_H */
vlc_cleanup_lock
static void vlc_cleanup_lock(void *lock)
Definition: vlc_threads.h:1049
vlc_timer::value
vlc_tick_t value
Definition: timer.c:66
vlc_cond_broadcast
VLC_EXPORT void vlc_cond_broadcast(vlc_cond_t *)
Wakes up all threads waiting on a condition variable.
Definition: threads.c:280
vlc_mutex_init
VLC_EXPORT void vlc_mutex_init(vlc_mutex_t *)
Initializes a fast mutex.
Definition: threads.c:123
VLC_XLIB_MUTEX
@ VLC_XLIB_MUTEX
Definition: vlc_threads.h:1087
count
size_t count
Definition: core.c:401
VLC_API
#define VLC_API
Definition: fourcc_gen.c:31
vlc_rwlock_rdlock
VLC_EXPORT void vlc_rwlock_rdlock(vlc_rwlock_t *)
Acquires a read/write lock for reading.
Definition: threads.c:394
vlc_mutex_t::owner
const void * owner
Definition: vlc_threads.h:238
VLC_MAX_MUTEX
@ VLC_MAX_MUTEX
Definition: vlc_threads.h:1093
vlc_global_mutex
VLC_EXPORT void vlc_global_mutex(unsigned, bool)
Internal handler for global mutexes.
Definition: threads.c:43
vlc_cleanup_t
struct vlc_cleanup_t vlc_cleanup_t
Definition: vlc_threads.h:784
vlc_thread_id
VLC_EXPORT unsigned long vlc_thread_id(void)
Thread identifier.
Definition: thread.c:36
vlc_sem_init
VLC_EXPORT void vlc_sem_init(vlc_sem_t *, unsigned count)
Initializes a semaphore.
Definition: threads.c:442
vlc_once_t::value
atomic_uint value
Definition: vlc_threads.h:581
unlikely
#define unlikely(p)
Predicted false condition.
Definition: vlc_common.h:227
vlc_common.h
vlc_atomic_timedwait_daytime
int vlc_atomic_timedwait_daytime(void *addr, unsigned val, time_t deadline)
Definition: thread.c:105
vlc_threadvar_t
pthread_key_t vlc_threadvar_t
Thread-local key handle.
Definition: vlc_threads.h:195
vlc_rwlock
Read/write lock.
Definition: vlc_threads.h:532
vlc_atomic_timedwait
int vlc_atomic_timedwait(void *addr, unsigned val, vlc_tick_t deadline)
Waits on an address with a time-out.
Definition: thread.c:84
pollfd
Definition: vlc_fixups.h:417
state
static thread_local struct @78 state
vlc_threadvar
Definition: thread.c:148
vlc_cond_wait
VLC_EXPORT void vlc_cond_wait(vlc_cond_t *cond, vlc_mutex_t *mutex)
Waits on a condition variable.
Definition: threads.c:340
vlc_timer_getoverrun
VLC_EXPORT unsigned vlc_timer_getoverrun(vlc_timer_t)
Fetches and resets the overrun counter for a timer.
Definition: thread.c:913
vlc_timer_disarm
static void vlc_timer_disarm(vlc_timer_t timer)
Definition: vlc_threads.h:961
vlc_tick_sleep
#define vlc_tick_sleep(d)
Definition: vlc_threads.h:902
poll
int poll(struct pollfd *, unsigned, int)
vlc_mutex_t::recursion
unsigned int recursion
Definition: vlc_threads.h:237
vlc_sem_t::value
atomic_uint value
Definition: vlc_threads.h:453
vlc_timer
Definition: thread.c:825
VLC_HARD_MIN_SLEEP
#define VLC_HARD_MIN_SLEEP
Definition: vlc_threads.h:849
vlc_timer::handle
HANDLE handle
Definition: timer.c:50
vlc_threadvar_set
VLC_EXPORT int vlc_threadvar_set(vlc_threadvar_t key, void *value)
Sets a thread-specific variable.
Definition: thread.c:250
VLC_TIMER_DISARM
#define VLC_TIMER_DISARM
Definition: vlc_threads.h:937
vlc_mutex_held
VLC_EXPORT bool vlc_mutex_held(const vlc_mutex_t *)
Checks if a mutex is locked.
Definition: threads.c:136
vlc_rwlock_t
struct vlc_rwlock vlc_rwlock_t
Read/write lock.
vlc_cancel_addr_clear
void vlc_cancel_addr_clear(atomic_uint *addr)
Definition: thread.c:225
vlc_cond_signal
VLC_EXPORT void vlc_cond_signal(vlc_cond_t *)
Wakes up one thread waiting on a condition variable.
Definition: threads.c:253
vlc_mutex_t
Mutex.
Definition: vlc_threads.h:225
VLC_MOSAIC_MUTEX
@ VLC_MOSAIC_MUTEX
Definition: vlc_threads.h:1088
vlc_timer_schedule
VLC_EXPORT void vlc_timer_schedule(vlc_timer_t timer, bool absolute, vlc_tick_t value, vlc_tick_t interval)
Arms or disarms an initialized timer.
Definition: thread.c:890
VLC_GCRYPT_MUTEX
@ VLC_GCRYPT_MUTEX
Definition: vlc_threads.h:1086
vlc_clone
VLC_EXPORT int vlc_clone(vlc_thread_t *th, void *(*entry)(void *), void *data, int priority)
Creates and starts a new thread.
Definition: thread.c:144
vlc_mutex_init_recursive
VLC_EXPORT void vlc_mutex_init_recursive(vlc_mutex_t *)
Initializes a recursive mutex.
Definition: threads.c:128
vlc_savecancel
VLC_EXPORT int vlc_savecancel(void)
Disables thread cancellation.
Definition: thread.c:183
vlc_tick_now
VLC_EXPORT vlc_tick_t vlc_tick_now(void)
Precision monotonic clock.
Definition: thread.c:261
vlc_tick_t
int64_t vlc_tick_t
High precision date or time interval.
Definition: vlc_tick.h:45
vlc_rwlock::mutex
vlc_mutex_t mutex
Definition: vlc_threads.h:534
vlc_rwlock::wait
vlc_cond_t wait
Definition: vlc_threads.h:535
VLC_AVCODEC_MUTEX
@ VLC_AVCODEC_MUTEX
Definition: vlc_threads.h:1085
vlc_atomic_notify_all
void vlc_atomic_notify_all(void *addr)
Wakes up all thread on an address.
Definition: thread.c:72
lock
vlc_mutex_t lock
Definition: rand.c:50
vlc_once
#define vlc_once(once, cb)
Definition: vlc_threads.h:613
vlc_atomic_notify_one
void vlc_atomic_notify_one(void *addr)
Wakes up one thread on an address.
Definition: thread.c:67
vlc_threadvar_create
VLC_EXPORT int vlc_threadvar_create(vlc_threadvar_t *key, void(*destr)(void *))
Allocates a thread-specific variable.
Definition: thread.c:240
vlc_cancel_addr_set
void vlc_cancel_addr_set(atomic_uint *addr)
Definition: thread.c:213
vlc_thread_t
Thread handle.
Definition: vlc_threads.h:180
vlc_tick_wait
#define vlc_tick_wait(d)
Definition: vlc_threads.h:903
vlc_once_inline
VLC_EXPORT void vlc_once_inline(vlc_once_t *restrict once, void(*cb)(void))
Executes a function one time.
Definition: vlc_threads.h:607
vlc_mutex_t::recursion
atomic_uint recursion
Definition: vlc_threads.h:231
vlc_rwlock_unlock
VLC_EXPORT void vlc_rwlock_unlock(vlc_rwlock_t *)
Releases a read/write lock.
Definition: threads.c:420
vlc_threadvar_get
VLC_EXPORT void * vlc_threadvar_get(vlc_threadvar_t)
Gets the value of a thread-local variable for the calling thread.
Definition: thread.c:255
vlc_restorecancel
VLC_EXPORT void vlc_restorecancel(int state)
Restores the cancellation state.
Definition: thread.c:193
vlc_sem_t::dummy
int dummy
Definition: vlc_threads.h:455
vlc_sem_wait
VLC_EXPORT void vlc_sem_wait(vlc_sem_t *)
Waits on a semaphore.
Definition: threads.c:463
vlc_cond_t::lock
vlc_mutex_t lock
Definition: vlc_threads.h:352
vlc_sem_t
Semaphore.
Definition: vlc_threads.h:449
vlc_timer_t
struct vlc_timer * vlc_timer_t
Threaded timer handle.
Definition: vlc_threads.h:202
vlc_cond_waiter::value
atomic_uint value
Definition: threads.c:242
VLC_USED
#define VLC_USED
Definition: fourcc_gen.c:32
vlc_sem_trywait
VLC_EXPORT int vlc_sem_trywait(vlc_sem_t *sem)
Tries to decrement a semaphore.
Definition: threads.c:500
vlc_mutex_t::value
unsigned int value
Definition: vlc_threads.h:236
vlc_mutex_lock
VLC_EXPORT void vlc_mutex_lock(vlc_mutex_t *)
Acquires a mutex.
Definition: threads.c:158
vlc_rwlock::state
long state
Definition: vlc_threads.h:536
vlc_timer_destroy
VLC_EXPORT void vlc_timer_destroy(vlc_timer_t timer)
Destroys an initialized timer.
Definition: thread.c:877
vlc_timer_schedule_asap
static void vlc_timer_schedule_asap(vlc_timer_t timer, vlc_tick_t interval)
Definition: vlc_threads.h:966
entry
Definition: fourcc_gen.c:51
vlc_cond_t
Condition variable.
Definition: vlc_threads.h:349
vlc_thread
Definition: thread.c:70
vlc_control_cancel
VLC_EXPORT void vlc_control_cancel(vlc_cleanup_t *)
Internal handler for thread cancellation.
Definition: missing.c:280
vlc_sem_post
VLC_EXPORT int vlc_sem_post(vlc_sem_t *)
Increments the value of a semaphore.
Definition: threads.c:447
vlc_atomic_wait
void vlc_atomic_wait(void *addr, unsigned val)
Waits on an address.
Definition: thread.c:77
vlc_once_t
One-time initialization.
Definition: vlc_threads.h:579
vlc_threadvar_delete
VLC_EXPORT void vlc_threadvar_delete(vlc_threadvar_t *)
Deallocates a thread-specific variable.
Definition: thread.c:245
vlc_rwlock_wrlock
VLC_EXPORT void vlc_rwlock_wrlock(vlc_rwlock_t *)
Acquires a read/write lock for writing.
Definition: threads.c:410
vlc_cond_t::head
struct vlc_cond_waiter * head
Definition: vlc_threads.h:351
vlc_sem_timedwait
VLC_EXPORT int vlc_sem_timedwait(vlc_sem_t *sem, vlc_tick_t deadline)
Waits on a semaphore within a deadline.
Definition: threads.c:479
vlc_mutex_trylock
VLC_EXPORT int vlc_mutex_trylock(vlc_mutex_t *)
Tries to acquire a mutex.
Definition: threads.c:178
vlc_rwlock_init
VLC_EXPORT void vlc_rwlock_init(vlc_rwlock_t *)
Initializes a read/write lock.
Definition: threads.c:387
vlc_thread_t::handle
pthread_t handle
Definition: vlc_threads.h:182
vlc_cond_init
VLC_EXPORT void vlc_cond_init(vlc_cond_t *)
Initializes a condition variable.
Definition: threads.c:234
vlc_cond_timedwait
VLC_EXPORT int vlc_cond_timedwait(vlc_cond_t *cond, vlc_mutex_t *mutex, vlc_tick_t deadline)
Waits on a condition variable up to a certain date.
Definition: threads.c:349
vlc_join
VLC_EXPORT void vlc_join(vlc_thread_t th, void **result)
Waits for a thread to complete (if needed), then destroys it.
Definition: thread.c:151
vlc_mutex_t::value
atomic_uint value
Definition: vlc_threads.h:230
vlc_mutex_unlock
VLC_EXPORT void vlc_mutex_unlock(vlc_mutex_t *)
Releases a mutex.
Definition: threads.c:209
vlc_cond_timedwait_daytime
int vlc_cond_timedwait_daytime(vlc_cond_t *, vlc_mutex_t *, time_t)
Definition: threads.c:362
vlc_cond_waiter
Definition: threads.c:240
vlc_timer_create
VLC_EXPORT int vlc_timer_create(vlc_timer_t *id, void(*func)(void *), void *data)
Initializes an asynchronous timer.
Definition: thread.c:857
vlc_testcancel
VLC_EXPORT void vlc_testcancel(void)
Issues an explicit deferred cancellation point.
Definition: thread.c:201
vlc_GetCPUCount
VLC_EXPORT unsigned vlc_GetCPUCount(void)
Count CPUs.
Definition: thread.c:273
vlc_cancel
VLC_EXPORT void vlc_cancel(vlc_thread_t)
Marks a thread as cancelled.
Definition: thread.c:167