1 /*****************************************************************************
2 * thread.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>
32 #include <vlc_atomic.h>
37 #include <unistd.h> /* fsync() */
43 # include <sys/syscall.h> /* SYS_gettid */
46 #ifdef HAVE_EXECINFO_H
47 # include <execinfo.h>
51 # include <sys/time.h> /* gettimeofday in vlc_cond_timedwait */
52 # include <mach/mach_init.h> /* mach_task_self in semaphores */
56 * Print a backtrace to the standard error for debugging purpose.
58 void vlc_trace (const char *fn, const char *file, unsigned line)
60 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
61 fflush (stderr); /* needed before switch to low-level I/O */
64 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
65 backtrace_symbols_fd (stack, len, 2);
70 static inline unsigned long vlc_threadid (void)
72 #if defined (__linux__)
73 /* glibc does not provide a call for this */
74 return syscall (SYS_gettid);
77 union { pthread_t th; unsigned long int i; } v = { };
78 v.th = pthread_self ();
85 /*****************************************************************************
86 * vlc_thread_fatal: Report an error from the threading layer
87 *****************************************************************************
88 * This is mostly meant for debugging.
89 *****************************************************************************/
91 vlc_thread_fatal (const char *action, int error,
92 const char *function, const char *file, unsigned line)
94 int canc = vlc_savecancel ();
95 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
96 action, error, vlc_threadid ());
97 vlc_trace (function, file, line);
99 /* Sometimes strerror_r() crashes too, so make sure we print an error
100 * message before we invoke it */
102 /* Avoid the strerror_r() prototype brain damage in glibc */
104 fprintf (stderr, " Error message: %m\n");
109 switch (strerror_r (error, buf, sizeof (buf)))
114 case ERANGE: /* should never happen */
115 msg = "unknown (too big to display)";
118 msg = "unknown (invalid error number)";
121 fprintf (stderr, " Error message: %s\n", msg);
125 vlc_restorecancel (canc);
129 # define VLC_THREAD_ASSERT( action ) \
131 vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
133 # define VLC_THREAD_ASSERT( action ) ((void)val)
136 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
137 /* This is not prototyped under glibc, though it exists. */
138 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
141 /*****************************************************************************
142 * vlc_mutex_init: initialize a mutex
143 *****************************************************************************/
144 void vlc_mutex_init( vlc_mutex_t *p_mutex )
146 pthread_mutexattr_t attr;
148 if (unlikely(pthread_mutexattr_init (&attr)))
151 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_NORMAL );
153 /* Create error-checking mutex to detect problems more easily. */
154 # if defined (__GLIBC__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 6)
155 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
157 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
160 if (unlikely(pthread_mutex_init (p_mutex, &attr)))
162 pthread_mutexattr_destroy( &attr );
165 /*****************************************************************************
166 * vlc_mutex_init: initialize a recursive mutex (Do not use)
167 *****************************************************************************/
168 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
170 pthread_mutexattr_t attr;
172 if (unlikely(pthread_mutexattr_init (&attr)))
174 #if defined (__GLIBC__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 6)
175 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
177 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
179 if (unlikely(pthread_mutex_init (p_mutex, &attr)))
181 pthread_mutexattr_destroy( &attr );
186 * Destroys a mutex. The mutex must not be locked.
188 * @param p_mutex mutex to destroy
189 * @return always succeeds
191 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
193 int val = pthread_mutex_destroy( p_mutex );
194 VLC_THREAD_ASSERT ("destroying mutex");
198 # ifdef HAVE_VALGRIND_VALGRIND_H
199 # include <valgrind/valgrind.h>
201 # define RUNNING_ON_VALGRIND (0)
204 void vlc_assert_locked (vlc_mutex_t *p_mutex)
206 if (RUNNING_ON_VALGRIND > 0)
208 assert (pthread_mutex_lock (p_mutex) == EDEADLK);
213 * Acquires a mutex. If needed, waits for any other thread to release it.
214 * Beware of deadlocks when locking multiple mutexes at the same time,
215 * or when using mutexes from callbacks.
216 * This function is not a cancellation-point.
218 * @param p_mutex mutex initialized with vlc_mutex_init() or
219 * vlc_mutex_init_recursive()
221 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
223 int val = pthread_mutex_lock( p_mutex );
224 VLC_THREAD_ASSERT ("locking mutex");
228 * Acquires a mutex if and only if it is not currently held by another thread.
229 * This function never sleeps and can be used in delay-critical code paths.
230 * This function is not a cancellation-point.
232 * <b>Beware</b>: If this function fails, then the mutex is held... by another
233 * thread. The calling thread must deal with the error appropriately. That
234 * typically implies postponing the operations that would have required the
235 * mutex. If the thread cannot defer those operations, then it must use
236 * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
238 * @param p_mutex mutex initialized with vlc_mutex_init() or
239 * vlc_mutex_init_recursive()
240 * @return 0 if the mutex could be acquired, an error code otherwise.
242 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
244 int val = pthread_mutex_trylock( p_mutex );
247 VLC_THREAD_ASSERT ("locking mutex");
252 * Releases a mutex (or crashes if the mutex is not locked by the caller).
253 * @param p_mutex mutex locked with vlc_mutex_lock().
255 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
257 int val = pthread_mutex_unlock( p_mutex );
258 VLC_THREAD_ASSERT ("unlocking mutex");
262 * Initializes a condition variable.
264 void vlc_cond_init (vlc_cond_t *p_condvar)
266 pthread_condattr_t attr;
268 if (unlikely(pthread_condattr_init (&attr)))
270 #if !defined (_POSIX_CLOCK_SELECTION)
271 /* Fairly outdated POSIX support (that was defined in 2001) */
272 # define _POSIX_CLOCK_SELECTION (-1)
274 #if (_POSIX_CLOCK_SELECTION >= 0)
275 /* NOTE: This must be the same clock as the one in mtime.c */
276 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
279 if (unlikely(pthread_cond_init (p_condvar, &attr)))
281 pthread_condattr_destroy (&attr);
285 * Initializes a condition variable.
286 * Contrary to vlc_cond_init(), the wall clock will be used as a reference for
287 * the vlc_cond_timedwait() time-out parameter.
289 void vlc_cond_init_daytime (vlc_cond_t *p_condvar)
291 if (unlikely(pthread_cond_init (p_condvar, NULL)))
296 * Destroys a condition variable. No threads shall be waiting or signaling the
298 * @param p_condvar condition variable to destroy
300 void vlc_cond_destroy (vlc_cond_t *p_condvar)
302 int val = pthread_cond_destroy( p_condvar );
303 VLC_THREAD_ASSERT ("destroying condition");
307 * Wakes up one thread waiting on a condition variable, if any.
308 * @param p_condvar condition variable
310 void vlc_cond_signal (vlc_cond_t *p_condvar)
312 int val = pthread_cond_signal( p_condvar );
313 VLC_THREAD_ASSERT ("signaling condition variable");
317 * Wakes up all threads (if any) waiting on a condition variable.
318 * @param p_cond condition variable
320 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
322 pthread_cond_broadcast (p_condvar);
326 * Waits for a condition variable. The calling thread will be suspended until
327 * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
328 * condition variable, the thread is cancelled with vlc_cancel(), or the
329 * system causes a "spurious" unsolicited wake-up.
331 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
332 * a recursive mutex. Although it is possible to use the same mutex for
333 * multiple condition, it is not valid to use different mutexes for the same
334 * condition variable at the same time from different threads.
336 * In case of thread cancellation, the mutex is always locked before
337 * cancellation proceeds.
339 * The canonical way to use a condition variable to wait for event foobar is:
341 vlc_mutex_lock (&lock);
342 mutex_cleanup_push (&lock); // release the mutex in case of cancellation
345 vlc_cond_wait (&wait, &lock);
347 --- foobar is now true, do something about it here --
349 vlc_cleanup_run (); // release the mutex
352 * @param p_condvar condition variable to wait on
353 * @param p_mutex mutex which is unlocked while waiting,
354 * then locked again when waking up.
355 * @param deadline <b>absolute</b> timeout
357 * @return 0 if the condition was signaled, an error code in case of timeout.
359 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
361 int val = pthread_cond_wait( p_condvar, p_mutex );
362 VLC_THREAD_ASSERT ("waiting on condition");
366 * Waits for a condition variable up to a certain date.
367 * This works like vlc_cond_wait(), except for the additional time-out.
369 * If the variable was initialized with vlc_cond_init(), the timeout has the
370 * same arbitrary origin as mdate(). If the variable was initialized with
371 * vlc_cond_init_daytime(), the timeout is expressed from the Unix epoch.
373 * @param p_condvar condition variable to wait on
374 * @param p_mutex mutex which is unlocked while waiting,
375 * then locked again when waking up.
376 * @param deadline <b>absolute</b> timeout
378 * @return 0 if the condition was signaled, an error code in case of timeout.
380 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
383 #if defined(__APPLE__) && !defined(__powerpc__) && !defined( __ppc__ ) && !defined( __ppc64__ )
384 /* mdate() is the monotonic clock, timedwait origin is gettimeofday() which
385 * isn't monotonic. Use imedwait_relative_np() instead
387 mtime_t base = mdate();
391 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
392 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
394 int val = pthread_cond_timedwait_relative_np(p_condvar, p_mutex, &ts);
395 if (val != ETIMEDOUT)
396 VLC_THREAD_ASSERT ("timed-waiting on condition");
399 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
400 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
401 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
402 if (val != ETIMEDOUT)
403 VLC_THREAD_ASSERT ("timed-waiting on condition");
409 * Initializes a semaphore.
411 void vlc_sem_init (vlc_sem_t *sem, unsigned value)
413 #if defined(__APPLE__)
414 if (unlikely(semaphore_create(mach_task_self(), sem, SYNC_POLICY_FIFO, value) != KERN_SUCCESS))
417 if (unlikely(sem_init (sem, 0, value)))
423 * Destroys a semaphore.
425 void vlc_sem_destroy (vlc_sem_t *sem)
429 #if defined(__APPLE__)
430 if (likely(semaphore_destroy(mach_task_self(), *sem) == KERN_SUCCESS))
435 if (likely(sem_destroy (sem) == 0))
441 VLC_THREAD_ASSERT ("destroying semaphore");
445 * Increments the value of a semaphore.
446 * @return 0 on success, EOVERFLOW in case of integer overflow
448 int vlc_sem_post (vlc_sem_t *sem)
452 #if defined(__APPLE__)
453 if (likely(semaphore_signal(*sem) == KERN_SUCCESS))
458 if (likely(sem_post (sem) == 0))
464 if (unlikely(val != EOVERFLOW))
465 VLC_THREAD_ASSERT ("unlocking semaphore");
470 * Atomically wait for the semaphore to become non-zero (if needed),
471 * then decrements it.
473 void vlc_sem_wait (vlc_sem_t *sem)
477 #if defined(__APPLE__)
478 if (likely(semaphore_wait(*sem) == KERN_SUCCESS))
484 if (likely(sem_wait (sem) == 0))
486 while ((val = errno) == EINTR);
489 VLC_THREAD_ASSERT ("locking semaphore");
493 * Initializes a read/write lock.
495 void vlc_rwlock_init (vlc_rwlock_t *lock)
497 if (unlikely(pthread_rwlock_init (lock, NULL)))
502 * Destroys an initialized unused read/write lock.
504 void vlc_rwlock_destroy (vlc_rwlock_t *lock)
506 int val = pthread_rwlock_destroy (lock);
507 VLC_THREAD_ASSERT ("destroying R/W lock");
511 * Acquires a read/write lock for reading. Recursion is allowed.
513 void vlc_rwlock_rdlock (vlc_rwlock_t *lock)
515 int val = pthread_rwlock_rdlock (lock);
516 VLC_THREAD_ASSERT ("acquiring R/W lock for reading");
520 * Acquires a read/write lock for writing. Recursion is not allowed.
522 void vlc_rwlock_wrlock (vlc_rwlock_t *lock)
524 int val = pthread_rwlock_wrlock (lock);
525 VLC_THREAD_ASSERT ("acquiring R/W lock for writing");
529 * Releases a read/write lock.
531 void vlc_rwlock_unlock (vlc_rwlock_t *lock)
533 int val = pthread_rwlock_unlock (lock);
534 VLC_THREAD_ASSERT ("releasing R/W lock");
538 * Allocates a thread-specific variable.
539 * @param key where to store the thread-specific variable handle
540 * @param destr a destruction callback. It is called whenever a thread exits
541 * and the thread-specific variable has a non-NULL value.
542 * @return 0 on success, a system error code otherwise. This function can
543 * actually fail because there is a fixed limit on the number of
544 * thread-specific variable in a process on most systems.
546 int vlc_threadvar_create (vlc_threadvar_t *key, void (*destr) (void *))
548 return pthread_key_create (key, destr);
551 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
553 pthread_key_delete (*p_tls);
557 * Sets a thread-specific variable.
558 * @param key thread-local variable key (created with vlc_threadvar_create())
559 * @param value new value for the variable for the calling thread
560 * @return 0 on success, a system error code otherwise.
562 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
564 return pthread_setspecific (key, value);
568 * Gets the value of a thread-local variable for the calling thread.
569 * This function cannot fail.
570 * @return the value associated with the given variable for the calling
571 * or NULL if there is no value.
573 void *vlc_threadvar_get (vlc_threadvar_t key)
575 return pthread_getspecific (key);
578 static bool rt_priorities = false;
579 static int rt_offset;
581 void vlc_threads_setup (libvlc_int_t *p_libvlc)
583 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
584 static bool initialized = false;
586 vlc_mutex_lock (&lock);
587 /* Initializes real-time priorities before any thread is created,
588 * just once per process. */
592 if (var_InheritBool (p_libvlc, "rt-priority"))
595 rt_offset = var_InheritInteger (p_libvlc, "rt-offset");
596 rt_priorities = true;
600 vlc_mutex_unlock (&lock);
604 static int vlc_clone_attr (vlc_thread_t *th, pthread_attr_t *attr,
605 void *(*entry) (void *), void *data, int priority)
609 /* Block the signals that signals interface plugin handles.
610 * If the LibVLC caller wants to handle some signals by itself, it should
611 * block these before whenever invoking LibVLC. And it must obviously not
612 * start the VLC signals interface plugin.
614 * LibVLC will normally ignore any interruption caused by an asynchronous
615 * signal during a system call. But there may well be some buggy cases
616 * where it fails to handle EINTR (bug reports welcome). Some underlying
617 * libraries might also not handle EINTR properly.
623 sigdelset (&set, SIGHUP);
624 sigaddset (&set, SIGINT);
625 sigaddset (&set, SIGQUIT);
626 sigaddset (&set, SIGTERM);
628 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
629 pthread_sigmask (SIG_BLOCK, &set, &oldset);
632 #if defined (_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING >= 0) \
633 && defined (_POSIX_THREAD_PRIORITY_SCHEDULING) \
634 && (_POSIX_THREAD_PRIORITY_SCHEDULING >= 0)
637 struct sched_param sp = { .sched_priority = priority + rt_offset, };
640 if (sp.sched_priority <= 0)
641 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
643 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
645 pthread_attr_setschedpolicy (attr, policy);
646 pthread_attr_setschedparam (attr, &sp);
652 /* The thread stack size.
653 * The lower the value, the less address space per thread, the highest
654 * maximum simultaneous threads per process. Too low values will cause
655 * stack overflows and weird crashes. Set with caution. Also keep in mind
656 * that 64-bits platforms consume more stack than 32-bits one.
658 * Thanks to on-demand paging, thread stack size only affects address space
659 * consumption. In terms of memory, threads only use what they need
660 * (rounded up to the page boundary).
662 * For example, on Linux i386, the default is 2 mega-bytes, which supports
663 * about 320 threads per processes. */
664 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
667 ret = pthread_attr_setstacksize (attr, VLC_STACKSIZE);
668 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
671 ret = pthread_create (th, attr, entry, data);
672 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
673 pthread_attr_destroy (attr);
678 * Creates and starts new thread.
680 * The thread must be <i>joined</i> with vlc_join() to reclaim resources
681 * when it is not needed anymore.
683 * @param th [OUT] pointer to write the handle of the created thread to
684 * (mandatory, must be non-NULL)
685 * @param entry entry point for the thread
686 * @param data data parameter given to the entry point
687 * @param priority thread priority value
688 * @return 0 on success, a standard error code on error.
690 int vlc_clone (vlc_thread_t *th, void *(*entry) (void *), void *data,
695 pthread_attr_init (&attr);
696 return vlc_clone_attr (th, &attr, entry, data, priority);
700 * Waits for a thread to complete (if needed), then destroys it.
701 * This is a cancellation point; in case of cancellation, the join does _not_
704 * A thread cannot join itself (normally VLC will abort if this is attempted).
705 * Also, a detached thread <b>cannot</b> be joined.
707 * @param handle thread handle
708 * @param p_result [OUT] pointer to write the thread return value or NULL
710 void vlc_join (vlc_thread_t handle, void **result)
712 int val = pthread_join (handle, result);
713 VLC_THREAD_ASSERT ("joining thread");
717 * Creates and starts new detached thread.
718 * A detached thread cannot be joined. Its resources will be automatically
719 * released whenever the thread exits (in particular, its call stack will be
722 * Detached thread are particularly useful when some work needs to be done
723 * asynchronously, that is likely to be completed much earlier than the thread
724 * can practically be joined. In this case, thread detach can spare memory.
726 * A detached thread may be cancelled, so as to expedite its termination.
727 * Be extremely careful if you do this: while a normal joinable thread can
728 * safely be cancelled after it has already exited, cancelling an already
729 * exited detached thread is undefined: The thread handle would is destroyed
730 * immediately when the detached thread exits. So you need to ensure that the
731 * detached thread is still running before cancellation is attempted.
733 * @warning Care must be taken that any resources used by the detached thread
734 * remains valid until the thread completes.
736 * @note A detached thread must eventually exit just like another other
737 * thread. In practice, LibVLC will wait for detached threads to exit before
738 * it unloads the plugins.
740 * @param th [OUT] pointer to hold the thread handle, or NULL
741 * @param entry entry point for the thread
742 * @param data data parameter given to the entry point
743 * @param priority thread priority value
744 * @return 0 on success, a standard error code on error.
746 int vlc_clone_detach (vlc_thread_t *th, void *(*entry) (void *), void *data,
755 pthread_attr_init (&attr);
756 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
757 return vlc_clone_attr (th, &attr, entry, data, priority);
761 * Marks a thread as cancelled. Next time the target thread reaches a
762 * cancellation point (while not having disabled cancellation), it will
763 * run its cancellation cleanup handler, the thread variable destructors, and
764 * terminate. vlc_join() must be used afterward regardless of a thread being
767 void vlc_cancel (vlc_thread_t thread_id)
769 pthread_cancel (thread_id);
771 pthread_kill (thread_id, SIGRTMIN);
776 * Save the current cancellation state (enabled or disabled), then disable
777 * cancellation for the calling thread.
778 * This function must be called before entering a piece of code that is not
779 * cancellation-safe, unless it can be proven that the calling thread will not
781 * @return Previous cancellation state (opaque value for vlc_restorecancel()).
783 int vlc_savecancel (void)
786 int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
788 VLC_THREAD_ASSERT ("saving cancellation");
793 * Restore the cancellation state for the calling thread.
794 * @param state previous state as returned by vlc_savecancel().
795 * @return Nothing, always succeeds.
797 void vlc_restorecancel (int state)
802 val = pthread_setcancelstate (state, &oldstate);
803 /* This should fail if an invalid value for given for state */
804 VLC_THREAD_ASSERT ("restoring cancellation");
806 if (unlikely(oldstate != PTHREAD_CANCEL_DISABLE))
807 vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
808 __func__, __FILE__, __LINE__);
810 pthread_setcancelstate (state, NULL);
815 * Issues an explicit deferred cancellation point.
816 * This has no effect if thread cancellation is disabled.
817 * This can be called when there is a rather slow non-sleeping operation.
818 * This is also used to force a cancellation point in a function that would
819 * otherwise "not always" be a one (block_FifoGet() is an example).
821 void vlc_testcancel (void)
823 pthread_testcancel ();
826 void vlc_control_cancel (int cmd, ...)
836 vlc_cond_t reschedule;
838 void (*func) (void *);
840 mtime_t value, interval;
841 vlc_atomic_t overruns;
844 static void *vlc_timer_thread (void *data)
846 struct vlc_timer *timer = data;
848 vlc_mutex_lock (&timer->lock);
849 mutex_cleanup_push (&timer->lock);
853 while (timer->value == 0)
854 vlc_cond_wait (&timer->reschedule, &timer->lock);
856 if (vlc_cond_timedwait (&timer->reschedule, &timer->lock,
859 if (timer->interval == 0)
860 timer->value = 0; /* disarm */
861 vlc_mutex_unlock (&timer->lock);
863 int canc = vlc_savecancel ();
864 timer->func (timer->data);
865 vlc_restorecancel (canc);
867 mtime_t now = mdate ();
870 vlc_mutex_lock (&timer->lock);
871 if (timer->interval == 0)
874 misses = (now - timer->value) / timer->interval;
875 timer->value += timer->interval;
876 /* Try to compensate for one miss (mwait() will return immediately)
877 * but no more. Otherwise, we might busy loop, after extended periods
878 * without scheduling (suspend, SIGSTOP, RT preemption, ...). */
882 timer->value += misses * timer->interval;
883 vlc_atomic_add (&timer->overruns, misses);
892 * Initializes an asynchronous timer.
893 * @warning Asynchronous timers are processed from an unspecified thread.
894 * Multiple occurences of a single interval timer are serialized; they cannot
897 * @param id pointer to timer to be initialized
898 * @param func function that the timer will call
899 * @param data parameter for the timer function
900 * @return 0 on success, a system error code otherwise.
902 int vlc_timer_create (vlc_timer_t *id, void (*func) (void *), void *data)
904 struct vlc_timer *timer = malloc (sizeof (*timer));
906 if (unlikely(timer == NULL))
908 vlc_mutex_init (&timer->lock);
909 vlc_cond_init (&timer->reschedule);
915 vlc_atomic_set(&timer->overruns, 0);
917 if (vlc_clone (&timer->thread, vlc_timer_thread, timer,
918 VLC_THREAD_PRIORITY_INPUT))
920 vlc_cond_destroy (&timer->reschedule);
921 vlc_mutex_destroy (&timer->lock);
931 * Destroys an initialized timer. If needed, the timer is first disarmed.
932 * This function is undefined if the specified timer is not initialized.
934 * @warning This function <b>must</b> be called before the timer data can be
935 * freed and before the timer callback function can be unloaded.
937 * @param timer timer to destroy
939 void vlc_timer_destroy (vlc_timer_t timer)
941 vlc_cancel (timer->thread);
942 vlc_join (timer->thread, NULL);
943 vlc_cond_destroy (&timer->reschedule);
944 vlc_mutex_destroy (&timer->lock);
949 * Arm or disarm an initialized timer.
950 * This functions overrides any previous call to itself.
952 * @note A timer can fire later than requested due to system scheduling
953 * limitations. An interval timer can fail to trigger sometimes, either because
954 * the system is busy or suspended, or because a previous iteration of the
955 * timer is still running. See also vlc_timer_getoverrun().
957 * @param timer initialized timer
958 * @param absolute the timer value origin is the same as mdate() if true,
959 * the timer value is relative to now if false.
960 * @param value zero to disarm the timer, otherwise the initial time to wait
961 * before firing the timer.
962 * @param interval zero to fire the timer just once, otherwise the timer
963 * repetition interval.
965 void vlc_timer_schedule (vlc_timer_t timer, bool absolute,
966 mtime_t value, mtime_t interval)
968 if (!absolute && value != 0)
971 vlc_mutex_lock (&timer->lock);
972 timer->value = value;
973 timer->interval = interval;
974 vlc_cond_signal (&timer->reschedule);
975 vlc_mutex_unlock (&timer->lock);
979 * Fetch and reset the overrun counter for a timer.
980 * @param timer initialized timer
981 * @return the timer overrun counter, i.e. the number of times that the timer
982 * should have run but did not since the last actual run. If all is well, this
985 unsigned vlc_timer_getoverrun (vlc_timer_t timer)
987 return vlc_atomic_swap (&timer->overruns, 0);