1 /*****************************************************************************
2 * pthread.c : pthread back-end for LibVLC
3 *****************************************************************************
4 * Copyright (C) 1999-2009 the VideoLAN team
6 * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
7 * Samuel Hocevar <sam@zoy.org>
8 * Gildas Bazin <gbazin@netcourrier.com>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
31 #include <vlc_common.h>
36 #include <unistd.h> /* fsync() */
42 # include <sys/syscall.h> /* SYS_gettid */
45 #ifdef HAVE_EXECINFO_H
46 # include <execinfo.h>
50 # include <sys/time.h> /* gettimeofday in vlc_cond_timedwait */
51 # include <mach/mach_init.h> /* mach_task_self in semaphores */
55 * Print a backtrace to the standard error for debugging purpose.
57 void vlc_trace (const char *fn, const char *file, unsigned line)
59 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
60 fflush (stderr); /* needed before switch to low-level I/O */
63 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
64 backtrace_symbols_fd (stack, len, 2);
69 static inline unsigned long vlc_threadid (void)
71 #if defined (__linux__)
72 /* glibc does not provide a call for this */
73 return syscall (SYS_gettid);
76 union { pthread_t th; unsigned long int i; } v = { };
77 v.th = pthread_self ();
84 /*****************************************************************************
85 * vlc_thread_fatal: Report an error from the threading layer
86 *****************************************************************************
87 * This is mostly meant for debugging.
88 *****************************************************************************/
90 vlc_thread_fatal (const char *action, int error,
91 const char *function, const char *file, unsigned line)
93 int canc = vlc_savecancel ();
94 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
95 action, error, vlc_threadid ());
96 vlc_trace (function, file, line);
98 /* Sometimes strerror_r() crashes too, so make sure we print an error
99 * message before we invoke it */
101 /* Avoid the strerror_r() prototype brain damage in glibc */
103 fprintf (stderr, " Error message: %m\n");
108 switch (strerror_r (error, buf, sizeof (buf)))
113 case ERANGE: /* should never happen */
114 msg = "unknwon (too big to display)";
117 msg = "unknown (invalid error number)";
120 fprintf (stderr, " Error message: %s\n", msg);
124 vlc_restorecancel (canc);
128 # define VLC_THREAD_ASSERT( action ) \
130 vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
132 # define VLC_THREAD_ASSERT( action ) ((void)val)
135 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
136 /* This is not prototyped under glibc, though it exists. */
137 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
140 /*****************************************************************************
141 * vlc_mutex_init: initialize a mutex
142 *****************************************************************************/
143 void vlc_mutex_init( vlc_mutex_t *p_mutex )
145 pthread_mutexattr_t attr;
147 if (unlikely(pthread_mutexattr_init (&attr)))
150 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_NORMAL );
152 /* Create error-checking mutex to detect problems more easily. */
153 # if defined (__GLIBC__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 6)
154 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
156 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
159 if (unlikely(pthread_mutex_init (p_mutex, &attr)))
161 pthread_mutexattr_destroy( &attr );
164 /*****************************************************************************
165 * vlc_mutex_init: initialize a recursive mutex (Do not use)
166 *****************************************************************************/
167 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
169 pthread_mutexattr_t attr;
171 if (unlikely(pthread_mutexattr_init (&attr)))
173 #if defined (__GLIBC__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 6)
174 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
176 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
178 if (unlikely(pthread_mutex_init (p_mutex, &attr)))
180 pthread_mutexattr_destroy( &attr );
185 * Destroys a mutex. The mutex must not be locked.
187 * @param p_mutex mutex to destroy
188 * @return always succeeds
190 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
192 int val = pthread_mutex_destroy( p_mutex );
193 VLC_THREAD_ASSERT ("destroying mutex");
197 # ifdef HAVE_VALGRIND_VALGRIND_H
198 # include <valgrind/valgrind.h>
200 # define RUNNING_ON_VALGRIND (0)
203 void vlc_assert_locked (vlc_mutex_t *p_mutex)
205 if (RUNNING_ON_VALGRIND > 0)
207 assert (pthread_mutex_lock (p_mutex) == EDEADLK);
212 * Acquires a mutex. If needed, waits for any other thread to release it.
213 * Beware of deadlocks when locking multiple mutexes at the same time,
214 * or when using mutexes from callbacks.
215 * This function is not a cancellation-point.
217 * @param p_mutex mutex initialized with vlc_mutex_init() or
218 * vlc_mutex_init_recursive()
220 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
222 int val = pthread_mutex_lock( p_mutex );
223 VLC_THREAD_ASSERT ("locking mutex");
227 * Acquires a mutex if and only if it is not currently held by another thread.
228 * This function never sleeps and can be used in delay-critical code paths.
229 * This function is not a cancellation-point.
231 * <b>Beware</b>: If this function fails, then the mutex is held... by another
232 * thread. The calling thread must deal with the error appropriately. That
233 * typically implies postponing the operations that would have required the
234 * mutex. If the thread cannot defer those operations, then it must use
235 * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
237 * @param p_mutex mutex initialized with vlc_mutex_init() or
238 * vlc_mutex_init_recursive()
239 * @return 0 if the mutex could be acquired, an error code otherwise.
241 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
243 int val = pthread_mutex_trylock( p_mutex );
246 VLC_THREAD_ASSERT ("locking mutex");
251 * Releases a mutex (or crashes if the mutex is not locked by the caller).
252 * @param p_mutex mutex locked with vlc_mutex_lock().
254 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
256 int val = pthread_mutex_unlock( p_mutex );
257 VLC_THREAD_ASSERT ("unlocking mutex");
261 * Initializes a condition variable.
263 void vlc_cond_init (vlc_cond_t *p_condvar)
265 pthread_condattr_t attr;
267 if (unlikely(pthread_condattr_init (&attr)))
269 #if !defined (_POSIX_CLOCK_SELECTION)
270 /* Fairly outdated POSIX support (that was defined in 2001) */
271 # define _POSIX_CLOCK_SELECTION (-1)
273 #if (_POSIX_CLOCK_SELECTION >= 0)
274 /* NOTE: This must be the same clock as the one in mtime.c */
275 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
278 if (unlikely(pthread_cond_init (p_condvar, &attr)))
280 pthread_condattr_destroy (&attr);
284 * Initializes a condition variable.
285 * Contrary to vlc_cond_init(), the wall clock will be used as a reference for
286 * the vlc_cond_timedwait() time-out parameter.
288 void vlc_cond_init_daytime (vlc_cond_t *p_condvar)
290 if (unlikely(pthread_cond_init (p_condvar, NULL)))
295 * Destroys a condition variable. No threads shall be waiting or signaling the
297 * @param p_condvar condition variable to destroy
299 void vlc_cond_destroy (vlc_cond_t *p_condvar)
301 int val = pthread_cond_destroy( p_condvar );
302 VLC_THREAD_ASSERT ("destroying condition");
306 * Wakes up one thread waiting on a condition variable, if any.
307 * @param p_condvar condition variable
309 void vlc_cond_signal (vlc_cond_t *p_condvar)
311 int val = pthread_cond_signal( p_condvar );
312 VLC_THREAD_ASSERT ("signaling condition variable");
316 * Wakes up all threads (if any) waiting on a condition variable.
317 * @param p_cond condition variable
319 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
321 pthread_cond_broadcast (p_condvar);
325 * Waits for a condition variable. The calling thread will be suspended until
326 * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
327 * condition variable, the thread is cancelled with vlc_cancel(), or the
328 * system causes a "spurious" unsolicited wake-up.
330 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
331 * a recursive mutex. Although it is possible to use the same mutex for
332 * multiple condition, it is not valid to use different mutexes for the same
333 * condition variable at the same time from different threads.
335 * In case of thread cancellation, the mutex is always locked before
336 * cancellation proceeds.
338 * The canonical way to use a condition variable to wait for event foobar is:
340 vlc_mutex_lock (&lock);
341 mutex_cleanup_push (&lock); // release the mutex in case of cancellation
344 vlc_cond_wait (&wait, &lock);
346 --- foobar is now true, do something about it here --
348 vlc_cleanup_run (); // release the mutex
351 * @param p_condvar condition variable to wait on
352 * @param p_mutex mutex which is unlocked while waiting,
353 * then locked again when waking up.
354 * @param deadline <b>absolute</b> timeout
356 * @return 0 if the condition was signaled, an error code in case of timeout.
358 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
360 int val = pthread_cond_wait( p_condvar, p_mutex );
361 VLC_THREAD_ASSERT ("waiting on condition");
365 * Waits for a condition variable up to a certain date.
366 * This works like vlc_cond_wait(), except for the additional time-out.
368 * If the variable was initialized with vlc_cond_init(), the timeout has the
369 * same arbitrary origin as mdate(). If the variable was initialized with
370 * vlc_cond_init_daytime(), the timeout is expressed from the Unix epoch.
372 * @param p_condvar condition variable to wait on
373 * @param p_mutex mutex which is unlocked while waiting,
374 * then locked again when waking up.
375 * @param deadline <b>absolute</b> timeout
377 * @return 0 if the condition was signaled, an error code in case of timeout.
379 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
382 #if defined(__APPLE__) && !defined(__powerpc__) && !defined( __ppc__ ) && !defined( __ppc64__ )
383 /* mdate() is mac_absolute_time on OSX, which we must convert to do
384 * the same base than gettimeofday() which pthread_cond_timedwait
386 mtime_t oldbase = mdate();
388 gettimeofday(&tv, NULL);
389 mtime_t newbase = (mtime_t)tv.tv_sec * 1000000 + (mtime_t) tv.tv_usec;
390 deadline = deadline - oldbase + newbase;
392 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
393 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
395 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
396 if (val != ETIMEDOUT)
397 VLC_THREAD_ASSERT ("timed-waiting on condition");
402 * Initializes a semaphore.
404 void vlc_sem_init (vlc_sem_t *sem, unsigned value)
406 #if defined(__APPLE__)
407 if (unlikely(semaphore_create(mach_task_self(), sem, SYNC_POLICY_FIFO, value) != KERN_SUCCESS))
410 if (unlikely(sem_init (sem, 0, value)))
416 * Destroys a semaphore.
418 void vlc_sem_destroy (vlc_sem_t *sem)
422 #if defined(__APPLE__)
423 if (likely(semaphore_destroy(mach_task_self(), *sem) == KERN_SUCCESS))
428 if (likely(sem_destroy (sem) == 0))
434 VLC_THREAD_ASSERT ("destroying semaphore");
438 * Increments the value of a semaphore.
439 * @return 0 on success, EOVERFLOW in case of integer overflow
441 int vlc_sem_post (vlc_sem_t *sem)
445 #if defined(__APPLE__)
446 if (likely(semaphore_signal(*sem) == KERN_SUCCESS))
451 if (likely(sem_post (sem) == 0))
457 if (unlikely(val != EOVERFLOW))
458 VLC_THREAD_ASSERT ("unlocking semaphore");
463 * Atomically wait for the semaphore to become non-zero (if needed),
464 * then decrements it.
466 void vlc_sem_wait (vlc_sem_t *sem)
470 #if defined(__APPLE__)
471 if (likely(semaphore_wait(*sem) == KERN_SUCCESS))
477 if (likely(sem_wait (sem) == 0))
479 while ((val = errno) == EINTR);
482 VLC_THREAD_ASSERT ("locking semaphore");
486 * Initializes a read/write lock.
488 void vlc_rwlock_init (vlc_rwlock_t *lock)
490 if (unlikely(pthread_rwlock_init (lock, NULL)))
495 * Destroys an initialized unused read/write lock.
497 void vlc_rwlock_destroy (vlc_rwlock_t *lock)
499 int val = pthread_rwlock_destroy (lock);
500 VLC_THREAD_ASSERT ("destroying R/W lock");
504 * Acquires a read/write lock for reading. Recursion is allowed.
506 void vlc_rwlock_rdlock (vlc_rwlock_t *lock)
508 int val = pthread_rwlock_rdlock (lock);
509 VLC_THREAD_ASSERT ("acquiring R/W lock for reading");
513 * Acquires a read/write lock for writing. Recursion is not allowed.
515 void vlc_rwlock_wrlock (vlc_rwlock_t *lock)
517 int val = pthread_rwlock_wrlock (lock);
518 VLC_THREAD_ASSERT ("acquiring R/W lock for writing");
522 * Releases a read/write lock.
524 void vlc_rwlock_unlock (vlc_rwlock_t *lock)
526 int val = pthread_rwlock_unlock (lock);
527 VLC_THREAD_ASSERT ("releasing R/W lock");
531 * Allocates a thread-specific variable.
532 * @param key where to store the thread-specific variable handle
533 * @param destr a destruction callback. It is called whenever a thread exits
534 * and the thread-specific variable has a non-NULL value.
535 * @return 0 on success, a system error code otherwise. This function can
536 * actually fail because there is a fixed limit on the number of
537 * thread-specific variable in a process on most systems.
539 int vlc_threadvar_create (vlc_threadvar_t *key, void (*destr) (void *))
541 return pthread_key_create (key, destr);
544 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
546 pthread_key_delete (*p_tls);
550 * Sets a thread-specific variable.
551 * @param key thread-local variable key (created with vlc_threadvar_create())
552 * @param value new value for the variable for the calling thread
553 * @return 0 on success, a system error code otherwise.
555 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
557 return pthread_setspecific (key, value);
561 * Gets the value of a thread-local variable for the calling thread.
562 * This function cannot fail.
563 * @return the value associated with the given variable for the calling
564 * or NULL if there is no value.
566 void *vlc_threadvar_get (vlc_threadvar_t key)
568 return pthread_getspecific (key);
571 static bool rt_priorities = false;
572 static int rt_offset;
574 void vlc_threads_setup (libvlc_int_t *p_libvlc)
576 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
577 static bool initialized = false;
579 vlc_mutex_lock (&lock);
580 /* Initializes real-time priorities before any thread is created,
581 * just once per process. */
585 if (var_InheritBool (p_libvlc, "rt-priority"))
588 rt_offset = var_InheritInteger (p_libvlc, "rt-offset");
589 rt_priorities = true;
593 vlc_mutex_unlock (&lock);
597 * Creates and starts new thread.
599 * @param p_handle [OUT] pointer to write the handle of the created thread to
600 * @param entry entry point for the thread
601 * @param data data parameter given to the entry point
602 * @param priority thread priority value
603 * @return 0 on success, a standard error code on error.
605 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
611 pthread_attr_init (&attr);
613 /* Block the signals that signals interface plugin handles.
614 * If the LibVLC caller wants to handle some signals by itself, it should
615 * block these before whenever invoking LibVLC. And it must obviously not
616 * start the VLC signals interface plugin.
618 * LibVLC will normally ignore any interruption caused by an asynchronous
619 * signal during a system call. But there may well be some buggy cases
620 * where it fails to handle EINTR (bug reports welcome). Some underlying
621 * libraries might also not handle EINTR properly.
627 sigdelset (&set, SIGHUP);
628 sigaddset (&set, SIGINT);
629 sigaddset (&set, SIGQUIT);
630 sigaddset (&set, SIGTERM);
632 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
633 pthread_sigmask (SIG_BLOCK, &set, &oldset);
636 #if defined (_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING >= 0) \
637 && defined (_POSIX_THREAD_PRIORITY_SCHEDULING) \
638 && (_POSIX_THREAD_PRIORITY_SCHEDULING >= 0)
641 struct sched_param sp = { .sched_priority = priority + rt_offset, };
644 if (sp.sched_priority <= 0)
645 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
647 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
649 pthread_attr_setschedpolicy (&attr, policy);
650 pthread_attr_setschedparam (&attr, &sp);
656 /* The thread stack size.
657 * The lower the value, the less address space per thread, the highest
658 * maximum simultaneous threads per process. Too low values will cause
659 * stack overflows and weird crashes. Set with caution. Also keep in mind
660 * that 64-bits platforms consume more stack than 32-bits one.
662 * Thanks to on-demand paging, thread stack size only affects address space
663 * consumption. In terms of memory, threads only use what they need
664 * (rounded up to the page boundary).
666 * For example, on Linux i386, the default is 2 mega-bytes, which supports
667 * about 320 threads per processes. */
668 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
671 ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
672 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
675 ret = pthread_create (p_handle, &attr, entry, data);
676 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
677 pthread_attr_destroy (&attr);
682 * Marks a thread as cancelled. Next time the target thread reaches a
683 * cancellation point (while not having disabled cancellation), it will
684 * run its cancellation cleanup handler, the thread variable destructors, and
685 * terminate. vlc_join() must be used afterward regardless of a thread being
688 void vlc_cancel (vlc_thread_t thread_id)
690 pthread_cancel (thread_id);
692 pthread_kill (thread_id, SIGRTMIN);
697 * Waits for a thread to complete (if needed), then destroys it.
698 * This is a cancellation point; in case of cancellation, the join does _not_
701 * A thread cannot join itself (normally VLC will abort if this is attempted).
702 * Also, a detached thread <b>cannot</b> be joined.
704 * @param handle thread handle
705 * @param p_result [OUT] pointer to write the thread return value or NULL
707 void vlc_join (vlc_thread_t handle, void **result)
709 int val = pthread_join (handle, result);
710 VLC_THREAD_ASSERT ("joining thread");
714 * Detaches a thread. When the specified thread completes, it will be
715 * automatically destroyed (in particular, its stack will be reclaimed),
716 * instead of waiting for another thread to call vlc_join(). If the thread has
717 * already completed, it will be destroyed immediately.
719 * When a thread performs some work asynchronously and may complete much
720 * earlier than it can be joined, detaching the thread can save memory.
721 * However, care must be taken that any resources used by a detached thread
722 * remains valid until the thread completes. This will typically involve some
723 * kind of thread-safe signaling.
725 * A thread may detach itself.
727 * @param handle thread handle
729 void vlc_detach (vlc_thread_t handle)
731 int val = pthread_detach (handle);
732 VLC_THREAD_ASSERT ("detaching thread");
736 * Save the current cancellation state (enabled or disabled), then disable
737 * cancellation for the calling thread.
738 * This function must be called before entering a piece of code that is not
739 * cancellation-safe, unless it can be proven that the calling thread will not
741 * @return Previous cancellation state (opaque value for vlc_restorecancel()).
743 int vlc_savecancel (void)
746 int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
748 VLC_THREAD_ASSERT ("saving cancellation");
753 * Restore the cancellation state for the calling thread.
754 * @param state previous state as returned by vlc_savecancel().
755 * @return Nothing, always succeeds.
757 void vlc_restorecancel (int state)
762 val = pthread_setcancelstate (state, &oldstate);
763 /* This should fail if an invalid value for given for state */
764 VLC_THREAD_ASSERT ("restoring cancellation");
766 if (unlikely(oldstate != PTHREAD_CANCEL_DISABLE))
767 vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
768 __func__, __FILE__, __LINE__);
770 pthread_setcancelstate (state, NULL);
775 * Issues an explicit deferred cancellation point.
776 * This has no effect if thread cancellation is disabled.
777 * This can be called when there is a rather slow non-sleeping operation.
778 * This is also used to force a cancellation point in a function that would
779 * otherwise "not always" be a one (block_FifoGet() is an example).
781 void vlc_testcancel (void)
783 pthread_testcancel ();
786 void vlc_control_cancel (int cmd, ...)
798 void (*func) (void *);
800 mtime_t value, interval;
805 static void *vlc_timer_do (void *data)
807 struct vlc_timer *timer = data;
809 timer->func (timer->data);
811 vlc_mutex_lock (&timer->lock);
812 assert (timer->users > 0);
813 if (--timer->users == 0)
814 vlc_cond_signal (&timer->wait);
815 vlc_mutex_unlock (&timer->lock);
819 static void *vlc_timer_thread (void *data)
821 struct vlc_timer *timer = data;
822 mtime_t value, interval;
824 vlc_mutex_lock (&timer->lock);
825 value = timer->value;
826 interval = timer->interval;
827 vlc_mutex_unlock (&timer->lock);
835 vlc_mutex_lock (&timer->lock);
836 if (vlc_clone (&th, vlc_timer_do, timer, VLC_THREAD_PRIORITY_INPUT))
843 vlc_mutex_unlock (&timer->lock);
853 * Initializes an asynchronous timer.
854 * @warning Asynchronous timers are processed from an unspecified thread.
855 * Also, multiple occurences of an interval timer can run concurrently.
857 * @param id pointer to timer to be initialized
858 * @param func function that the timer will call
859 * @param data parameter for the timer function
860 * @return 0 on success, a system error code otherwise.
862 int vlc_timer_create (vlc_timer_t *id, void (*func) (void *), void *data)
864 struct vlc_timer *timer = malloc (sizeof (*timer));
866 if (unlikely(timer == NULL))
868 vlc_mutex_init (&timer->lock);
869 vlc_cond_init (&timer->wait);
882 * Destroys an initialized timer. If needed, the timer is first disarmed.
883 * This function is undefined if the specified timer is not initialized.
885 * @warning This function <b>must</b> be called before the timer data can be
886 * freed and before the timer callback function can be unloaded.
888 * @param timer timer to destroy
890 void vlc_timer_destroy (vlc_timer_t timer)
892 vlc_timer_schedule (timer, false, 0, 0);
893 vlc_mutex_lock (&timer->lock);
894 while (timer->users != 0)
895 vlc_cond_wait (&timer->wait, &timer->lock);
896 vlc_mutex_unlock (&timer->lock);
898 vlc_cond_destroy (&timer->wait);
899 vlc_mutex_destroy (&timer->lock);
904 * Arm or disarm an initialized timer.
905 * This functions overrides any previous call to itself.
907 * @note A timer can fire later than requested due to system scheduling
908 * limitations. An interval timer can fail to trigger sometimes, either because
909 * the system is busy or suspended, or because a previous iteration of the
910 * timer is still running. See also vlc_timer_getoverrun().
912 * @param timer initialized timer
913 * @param absolute the timer value origin is the same as mdate() if true,
914 * the timer value is relative to now if false.
915 * @param value zero to disarm the timer, otherwise the initial time to wait
916 * before firing the timer.
917 * @param interval zero to fire the timer just once, otherwise the timer
918 * repetition interval.
920 void vlc_timer_schedule (vlc_timer_t timer, bool absolute,
921 mtime_t value, mtime_t interval)
923 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
925 vlc_mutex_lock (&lock);
926 vlc_mutex_lock (&timer->lock);
929 vlc_mutex_unlock (&timer->lock);
930 vlc_cancel (timer->thread);
931 vlc_join (timer->thread, NULL);
932 vlc_mutex_lock (&timer->lock);
936 && (vlc_clone (&timer->thread, vlc_timer_thread, timer,
937 VLC_THREAD_PRIORITY_INPUT) == 0))
939 timer->value = (absolute ? 0 : mdate ()) + value;
940 timer->interval = interval;
942 vlc_mutex_unlock (&timer->lock);
943 vlc_mutex_unlock (&lock);
947 * Fetch and reset the overrun counter for a timer.
948 * @param timer initialized timer
949 * @return the timer overrun counter, i.e. the number of times that the timer
950 * should have run but did not since the last actual run. If all is well, this
953 unsigned vlc_timer_getoverrun (vlc_timer_t timer)
957 vlc_mutex_lock (&timer->lock);
958 ret = timer->overruns;
960 vlc_mutex_unlock (&timer->lock);