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