]> git.sesse.net Git - vlc/blob - src/misc/pthread.c
58b2c8fbd3d983dcf0b36900bdfaaee5e9cbc595
[vlc] / src / misc / pthread.c
1 /*****************************************************************************
2  * pthread.c : pthread back-end for LibVLC
3  *****************************************************************************
4  * Copyright (C) 1999-2009 the VideoLAN team
5  *
6  * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
7  *          Samuel Hocevar <sam@zoy.org>
8  *          Gildas Bazin <gbazin@netcourrier.com>
9  *          Clément Sténac
10  *          Rémi Denis-Courmont
11  *
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.
16  *
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.
21  *
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  *****************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32
33 #include "libvlc.h"
34 #include <stdarg.h>
35 #include <assert.h>
36 #include <unistd.h> /* fsync() */
37 #include <signal.h>
38
39 #include <sched.h>
40 #ifdef __linux__
41 # include <sys/syscall.h> /* SYS_gettid */
42 #endif
43
44 #ifdef HAVE_EXECINFO_H
45 # include <execinfo.h>
46 #endif
47
48 #ifdef __APPLE__
49 # include <sys/time.h> /* gettimeofday in vlc_cond_timedwait */
50 #endif
51
52 /**
53  * Print a backtrace to the standard error for debugging purpose.
54  */
55 void vlc_trace (const char *fn, const char *file, unsigned line)
56 {
57      fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
58      fflush (stderr); /* needed before switch to low-level I/O */
59 #ifdef HAVE_BACKTRACE
60      void *stack[20];
61      int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
62      backtrace_symbols_fd (stack, len, 2);
63 #endif
64      fsync (2);
65 }
66
67 static inline unsigned long vlc_threadid (void)
68 {
69 #if defined (__linux__)
70      /* glibc does not provide a call for this */
71      return syscall (SYS_gettid);
72
73 #else
74      union { pthread_t th; unsigned long int i; } v = { };
75      v.th = pthread_self ();
76      return v.i;
77
78 #endif
79 }
80
81 #ifndef NDEBUG
82 /*****************************************************************************
83  * vlc_thread_fatal: Report an error from the threading layer
84  *****************************************************************************
85  * This is mostly meant for debugging.
86  *****************************************************************************/
87 static void
88 vlc_thread_fatal (const char *action, int error,
89                   const char *function, const char *file, unsigned line)
90 {
91     fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
92              action, error, vlc_threadid ());
93     vlc_trace (function, file, line);
94
95     /* Sometimes strerror_r() crashes too, so make sure we print an error
96      * message before we invoke it */
97 #ifdef __GLIBC__
98     /* Avoid the strerror_r() prototype brain damage in glibc */
99     errno = error;
100     fprintf (stderr, " Error message: %m\n");
101 #else
102     char buf[1000];
103     const char *msg;
104
105     switch (strerror_r (error, buf, sizeof (buf)))
106     {
107         case 0:
108             msg = buf;
109             break;
110         case ERANGE: /* should never happen */
111             msg = "unknwon (too big to display)";
112             break;
113         default:
114             msg = "unknown (invalid error number)";
115             break;
116     }
117     fprintf (stderr, " Error message: %s\n", msg);
118 #endif
119     fflush (stderr);
120
121     abort ();
122 }
123
124 # define VLC_THREAD_ASSERT( action ) \
125     if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
126 #else
127 # define VLC_THREAD_ASSERT( action ) ((void)val)
128 #endif
129
130 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
131 /* This is not prototyped under glibc, though it exists. */
132 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
133 #endif
134
135 /*****************************************************************************
136  * vlc_mutex_init: initialize a mutex
137  *****************************************************************************/
138 void vlc_mutex_init( vlc_mutex_t *p_mutex )
139 {
140     pthread_mutexattr_t attr;
141
142     if( pthread_mutexattr_init( &attr ) )
143         abort();
144 #ifndef NDEBUG
145     /* Create error-checking mutex to detect problems more easily. */
146 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
147     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
148 # else
149     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
150 # endif
151 #endif
152     if( pthread_mutex_init( p_mutex, &attr ) )
153         abort();
154     pthread_mutexattr_destroy( &attr );
155 }
156
157 /*****************************************************************************
158  * vlc_mutex_init: initialize a recursive mutex (Do not use)
159  *****************************************************************************/
160 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
161 {
162     pthread_mutexattr_t attr;
163
164     pthread_mutexattr_init( &attr );
165 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
166     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
167 #else
168     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
169 #endif
170     if( pthread_mutex_init( p_mutex, &attr ) )
171         abort();
172     pthread_mutexattr_destroy( &attr );
173 }
174
175
176 /**
177  * Destroys a mutex. The mutex must not be locked.
178  *
179  * @param p_mutex mutex to destroy
180  * @return always succeeds
181  */
182 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
183 {
184     int val = pthread_mutex_destroy( p_mutex );
185     VLC_THREAD_ASSERT ("destroying mutex");
186 }
187
188 #ifndef NDEBUG
189 # ifdef HAVE_VALGRIND_VALGRIND_H
190 #  include <valgrind/valgrind.h>
191 # else
192 #  define RUNNING_ON_VALGRIND (0)
193 # endif
194
195 void vlc_assert_locked (vlc_mutex_t *p_mutex)
196 {
197     if (RUNNING_ON_VALGRIND > 0)
198         return;
199     assert (pthread_mutex_lock (p_mutex) == EDEADLK);
200 }
201 #endif
202
203 /**
204  * Acquires a mutex. If needed, waits for any other thread to release it.
205  * Beware of deadlocks when locking multiple mutexes at the same time,
206  * or when using mutexes from callbacks.
207  * This function is not a cancellation-point.
208  *
209  * @param p_mutex mutex initialized with vlc_mutex_init() or
210  *                vlc_mutex_init_recursive()
211  */
212 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
213 {
214     int val = pthread_mutex_lock( p_mutex );
215     VLC_THREAD_ASSERT ("locking mutex");
216 }
217
218 /**
219  * Acquires a mutex if and only if it is not currently held by another thread.
220  * This function never sleeps and can be used in delay-critical code paths.
221  * This function is not a cancellation-point.
222  *
223  * <b>Beware</b>: If this function fails, then the mutex is held... by another
224  * thread. The calling thread must deal with the error appropriately. That
225  * typically implies postponing the operations that would have required the
226  * mutex. If the thread cannot defer those operations, then it must use
227  * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
228  *
229  * @param p_mutex mutex initialized with vlc_mutex_init() or
230  *                vlc_mutex_init_recursive()
231  * @return 0 if the mutex could be acquired, an error code otherwise.
232  */
233 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
234 {
235     int val = pthread_mutex_trylock( p_mutex );
236
237     if (val != EBUSY)
238         VLC_THREAD_ASSERT ("locking mutex");
239     return val;
240 }
241
242 /**
243  * Releases a mutex (or crashes if the mutex is not locked by the caller).
244  * @param p_mutex mutex locked with vlc_mutex_lock().
245  */
246 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
247 {
248     int val = pthread_mutex_unlock( p_mutex );
249     VLC_THREAD_ASSERT ("unlocking mutex");
250 }
251
252 /*****************************************************************************
253  * vlc_cond_init: initialize a condition variable
254  *****************************************************************************/
255 void vlc_cond_init( vlc_cond_t *p_condvar )
256 {
257     pthread_condattr_t attr;
258
259     if (pthread_condattr_init (&attr))
260         abort ();
261 #if !defined (_POSIX_CLOCK_SELECTION)
262    /* Fairly outdated POSIX support (that was defined in 2001) */
263 # define _POSIX_CLOCK_SELECTION (-1)
264 #endif
265 #if (_POSIX_CLOCK_SELECTION >= 0)
266     /* NOTE: This must be the same clock as the one in mtime.c */
267     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
268 #endif
269
270     if (pthread_cond_init (p_condvar, &attr))
271         abort ();
272     pthread_condattr_destroy (&attr);
273 }
274
275 /**
276  * Destroys a condition variable. No threads shall be waiting or signaling the
277  * condition.
278  * @param p_condvar condition variable to destroy
279  */
280 void vlc_cond_destroy (vlc_cond_t *p_condvar)
281 {
282     int val = pthread_cond_destroy( p_condvar );
283     VLC_THREAD_ASSERT ("destroying condition");
284 }
285
286 /**
287  * Wakes up one thread waiting on a condition variable, if any.
288  * @param p_condvar condition variable
289  */
290 void vlc_cond_signal (vlc_cond_t *p_condvar)
291 {
292     int val = pthread_cond_signal( p_condvar );
293     VLC_THREAD_ASSERT ("signaling condition variable");
294 }
295
296 /**
297  * Wakes up all threads (if any) waiting on a condition variable.
298  * @param p_cond condition variable
299  */
300 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
301 {
302     pthread_cond_broadcast (p_condvar);
303 }
304
305 /**
306  * Waits for a condition variable. The calling thread will be suspended until
307  * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
308  * condition variable, the thread is cancelled with vlc_cancel(), or the
309  * system causes a "spurious" unsolicited wake-up.
310  *
311  * A mutex is needed to wait on a condition variable. It must <b>not</b> be
312  * a recursive mutex. Although it is possible to use the same mutex for
313  * multiple condition, it is not valid to use different mutexes for the same
314  * condition variable at the same time from different threads.
315  *
316  * In case of thread cancellation, the mutex is always locked before
317  * cancellation proceeds.
318  *
319  * The canonical way to use a condition variable to wait for event foobar is:
320  @code
321    vlc_mutex_lock (&lock);
322    mutex_cleanup_push (&lock); // release the mutex in case of cancellation
323
324    while (!foobar)
325        vlc_cond_wait (&wait, &lock);
326
327    --- foobar is now true, do something about it here --
328
329    vlc_cleanup_run (); // release the mutex
330   @endcode
331  *
332  * @param p_condvar condition variable to wait on
333  * @param p_mutex mutex which is unlocked while waiting,
334  *                then locked again when waking up.
335  * @param deadline <b>absolute</b> timeout
336  *
337  * @return 0 if the condition was signaled, an error code in case of timeout.
338  */
339 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
340 {
341     int val = pthread_cond_wait( p_condvar, p_mutex );
342     VLC_THREAD_ASSERT ("waiting on condition");
343 }
344
345 /**
346  * Waits for a condition variable up to a certain date.
347  * This works like vlc_cond_wait(), except for the additional timeout.
348  *
349  * @param p_condvar condition variable to wait on
350  * @param p_mutex mutex which is unlocked while waiting,
351  *                then locked again when waking up.
352  * @param deadline <b>absolute</b> timeout
353  *
354  * @return 0 if the condition was signaled, an error code in case of timeout.
355  */
356 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
357                         mtime_t deadline)
358 {
359 #if defined(__APPLE__) && !defined(__powerpc__) && !defined( __ppc__ ) && !defined( __ppc64__ )
360     /* mdate() is mac_absolute_time on OSX, which we must convert to do
361      * the same base than gettimeofday() which pthread_cond_timedwait
362      * relies on. */
363     mtime_t oldbase = mdate();
364     struct timeval tv;
365     gettimeofday(&tv, NULL);
366     mtime_t newbase = (mtime_t)tv.tv_sec * 1000000 + (mtime_t) tv.tv_usec;
367     deadline = deadline - oldbase + newbase;
368 #endif
369     lldiv_t d = lldiv( deadline, CLOCK_FREQ );
370     struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
371
372     int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
373     if (val != ETIMEDOUT)
374         VLC_THREAD_ASSERT ("timed-waiting on condition");
375     return val;
376 }
377
378 /**
379  * Initializes a read/write lock.
380  */
381 void vlc_rwlock_init (vlc_rwlock_t *lock)
382 {
383     if (pthread_rwlock_init (lock, NULL))
384         abort ();
385 }
386
387 /**
388  * Destroys an initialized unused read/write lock.
389  */
390 void vlc_rwlock_destroy (vlc_rwlock_t *lock)
391 {
392     int val = pthread_rwlock_destroy (lock);
393     VLC_THREAD_ASSERT ("destroying R/W lock");
394 }
395
396 /**
397  * Acquires a read/write lock for reading. Recursion is allowed.
398  */
399 void vlc_rwlock_rdlock (vlc_rwlock_t *lock)
400 {
401     int val = pthread_rwlock_rdlock (lock);
402     VLC_THREAD_ASSERT ("acquiring R/W lock for reading");
403 }
404
405 /**
406  * Acquires a read/write lock for writing. Recursion is not allowed.
407  */
408 void vlc_rwlock_wrlock (vlc_rwlock_t *lock)
409 {
410     int val = pthread_rwlock_wrlock (lock);
411     VLC_THREAD_ASSERT ("acquiring R/W lock for writing");
412 }
413
414 /**
415  * Releases a read/write lock.
416  */
417 void vlc_rwlock_unlock (vlc_rwlock_t *lock)
418 {
419     int val = pthread_rwlock_unlock (lock);
420     VLC_THREAD_ASSERT ("releasing R/W lock");
421 }
422
423 /**
424  * Allocates a thread-specific variable.
425  * @param key where to store the thread-specific variable handle
426  * @param destr a destruction callback. It is called whenever a thread exits
427  * and the thread-specific variable has a non-NULL value.
428  * @return 0 on success, a system error code otherwise. This function can
429  * actually fail because there is a fixed limit on the number of
430  * thread-specific variable in a process on most systems.
431  */
432 int vlc_threadvar_create (vlc_threadvar_t *key, void (*destr) (void *))
433 {
434     return pthread_key_create (key, destr);
435 }
436
437 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
438 {
439     pthread_key_delete (*p_tls);
440 }
441
442 /**
443  * Sets a thread-specific variable.
444  * @param key thread-local variable key (created with vlc_threadvar_create())
445  * @param value new value for the variable for the calling thread
446  * @return 0 on success, a system error code otherwise.
447  */
448 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
449 {
450     return pthread_setspecific (key, value);
451 }
452
453 /**
454  * Gets the value of a thread-local variable for the calling thread.
455  * This function cannot fail.
456  * @return the value associated with the given variable for the calling
457  * or NULL if there is no value.
458  */
459 void *vlc_threadvar_get (vlc_threadvar_t key)
460 {
461     return pthread_getspecific (key);
462 }
463
464 static bool rt_priorities = false;
465 static int rt_offset;
466
467 void vlc_threads_setup (libvlc_int_t *p_libvlc)
468 {
469     static vlc_mutex_t lock = VLC_STATIC_MUTEX;
470     static bool initialized = false;
471
472     vlc_mutex_lock (&lock);
473     /* Initializes real-time priorities before any thread is created,
474      * just once per process. */
475     if (!initialized)
476     {
477 #ifndef __APPLE__
478         if (config_GetInt (p_libvlc, "rt-priority"))
479 #endif
480         {
481             rt_offset = config_GetInt (p_libvlc, "rt-offset");
482             rt_priorities = true;
483         }
484         initialized = true;
485     }
486     vlc_mutex_unlock (&lock);
487 }
488
489 /**
490  * Creates and starts new thread.
491  *
492  * @param p_handle [OUT] pointer to write the handle of the created thread to
493  * @param entry entry point for the thread
494  * @param data data parameter given to the entry point
495  * @param priority thread priority value
496  * @return 0 on success, a standard error code on error.
497  */
498 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
499                int priority)
500 {
501     int ret;
502
503     pthread_attr_t attr;
504     pthread_attr_init (&attr);
505
506     /* Block the signals that signals interface plugin handles.
507      * If the LibVLC caller wants to handle some signals by itself, it should
508      * block these before whenever invoking LibVLC. And it must obviously not
509      * start the VLC signals interface plugin.
510      *
511      * LibVLC will normally ignore any interruption caused by an asynchronous
512      * signal during a system call. But there may well be some buggy cases
513      * where it fails to handle EINTR (bug reports welcome). Some underlying
514      * libraries might also not handle EINTR properly.
515      */
516     sigset_t oldset;
517     {
518         sigset_t set;
519         sigemptyset (&set);
520         sigdelset (&set, SIGHUP);
521         sigaddset (&set, SIGINT);
522         sigaddset (&set, SIGQUIT);
523         sigaddset (&set, SIGTERM);
524
525         sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
526         pthread_sigmask (SIG_BLOCK, &set, &oldset);
527     }
528
529 #if defined (_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING >= 0) \
530  && defined (_POSIX_THREAD_PRIORITY_SCHEDULING) \
531  && (_POSIX_THREAD_PRIORITY_SCHEDULING >= 0)
532     if (rt_priorities)
533     {
534         struct sched_param sp = { .sched_priority = priority + rt_offset, };
535         int policy;
536
537         if (sp.sched_priority <= 0)
538             sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
539         else
540             sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
541
542         pthread_attr_setschedpolicy (&attr, policy);
543         pthread_attr_setschedparam (&attr, &sp);
544     }
545 #else
546     (void) priority;
547 #endif
548
549     /* The thread stack size.
550      * The lower the value, the less address space per thread, the highest
551      * maximum simultaneous threads per process. Too low values will cause
552      * stack overflows and weird crashes. Set with caution. Also keep in mind
553      * that 64-bits platforms consume more stack than 32-bits one.
554      *
555      * Thanks to on-demand paging, thread stack size only affects address space
556      * consumption. In terms of memory, threads only use what they need
557      * (rounded up to the page boundary).
558      *
559      * For example, on Linux i386, the default is 2 mega-bytes, which supports
560      * about 320 threads per processes. */
561 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
562
563 #ifdef VLC_STACKSIZE
564     ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
565     assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
566 #endif
567
568     ret = pthread_create (p_handle, &attr, entry, data);
569     pthread_sigmask (SIG_SETMASK, &oldset, NULL);
570     pthread_attr_destroy (&attr);
571     return ret;
572 }
573
574 /**
575  * Marks a thread as cancelled. Next time the target thread reaches a
576  * cancellation point (while not having disabled cancellation), it will
577  * run its cancellation cleanup handler, the thread variable destructors, and
578  * terminate. vlc_join() must be used afterward regardless of a thread being
579  * cancelled or not.
580  */
581 void vlc_cancel (vlc_thread_t thread_id)
582 {
583     pthread_cancel (thread_id);
584 }
585
586 /**
587  * Waits for a thread to complete (if needed), then destroys it.
588  * This is a cancellation point; in case of cancellation, the join does _not_
589  * occur.
590  * @warning
591  * A thread cannot join itself (normally VLC will abort if this is attempted).
592  * Also, a detached thread <b>cannot</b> be joined.
593  *
594  * @param handle thread handle
595  * @param p_result [OUT] pointer to write the thread return value or NULL
596  */
597 void vlc_join (vlc_thread_t handle, void **result)
598 {
599     int val = pthread_join (handle, result);
600     VLC_THREAD_ASSERT ("joining thread");
601 }
602
603 /**
604  * Detaches a thread. When the specified thread completes, it will be
605  * automatically destroyed (in particular, its stack will be reclaimed),
606  * instead of waiting for another thread to call vlc_join(). If the thread has
607  * already completed, it will be destroyed immediately.
608  *
609  * When a thread performs some work asynchronously and may complete much
610  * earlier than it can be joined, detaching the thread can save memory.
611  * However, care must be taken that any resources used by a detached thread
612  * remains valid until the thread completes. This will typically involve some
613  * kind of thread-safe signaling.
614  *
615  * A thread may detach itself.
616  *
617  * @param handle thread handle
618  */
619 void vlc_detach (vlc_thread_t handle)
620 {
621     int val = pthread_detach (handle);
622     VLC_THREAD_ASSERT ("detaching thread");
623 }
624
625 /**
626  * Save the current cancellation state (enabled or disabled), then disable
627  * cancellation for the calling thread.
628  * This function must be called before entering a piece of code that is not
629  * cancellation-safe, unless it can be proven that the calling thread will not
630  * be cancelled.
631  * @return Previous cancellation state (opaque value for vlc_restorecancel()).
632  */
633 int vlc_savecancel (void)
634 {
635     int state;
636     int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
637
638     VLC_THREAD_ASSERT ("saving cancellation");
639     return state;
640 }
641
642 /**
643  * Restore the cancellation state for the calling thread.
644  * @param state previous state as returned by vlc_savecancel().
645  * @return Nothing, always succeeds.
646  */
647 void vlc_restorecancel (int state)
648 {
649 #ifndef NDEBUG
650     int oldstate, val;
651
652     val = pthread_setcancelstate (state, &oldstate);
653     /* This should fail if an invalid value for given for state */
654     VLC_THREAD_ASSERT ("restoring cancellation");
655
656     if (oldstate != PTHREAD_CANCEL_DISABLE)
657          vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
658                            __func__, __FILE__, __LINE__);
659 #else
660     pthread_setcancelstate (state, NULL);
661 #endif
662 }
663
664 /**
665  * Issues an explicit deferred cancellation point.
666  * This has no effect if thread cancellation is disabled.
667  * This can be called when there is a rather slow non-sleeping operation.
668  * This is also used to force a cancellation point in a function that would
669  * otherwise "not always" be a one (block_FifoGet() is an example).
670  */
671 void vlc_testcancel (void)
672 {
673     pthread_testcancel ();
674 }
675
676 void vlc_control_cancel (int cmd, ...)
677 {
678     (void) cmd;
679     assert (0);
680 }
681
682
683 struct vlc_timer
684 {
685     vlc_thread_t thread;
686     vlc_mutex_t  lock;
687     vlc_cond_t   wait;
688     void       (*func) (void *);
689     void        *data;
690     mtime_t      value, interval;
691     unsigned     users;
692     unsigned     overruns;
693 };
694
695 static void *vlc_timer_do (void *data)
696 {
697     struct vlc_timer *timer = data;
698
699     timer->func (timer->data);
700
701     vlc_mutex_lock (&timer->lock);
702     assert (timer->users > 0);
703     if (--timer->users == 0)
704         vlc_cond_signal (&timer->wait);
705     vlc_mutex_unlock (&timer->lock);
706     return NULL;
707 }
708
709 static void *vlc_timer_thread (void *data)
710 {
711     struct vlc_timer *timer = data;
712     mtime_t value, interval;
713
714     vlc_mutex_lock (&timer->lock);
715     value = timer->value;
716     interval = timer->interval;
717     vlc_mutex_unlock (&timer->lock);
718
719     for (;;)
720     {
721          vlc_thread_t th;
722
723          mwait (value);
724
725          vlc_mutex_lock (&timer->lock);
726          if (vlc_clone (&th, vlc_timer_do, timer, VLC_THREAD_PRIORITY_INPUT))
727              timer->overruns++;
728          else
729          {
730              vlc_detach (th);
731              timer->users++;
732          }
733          vlc_mutex_unlock (&timer->lock);
734
735          if (interval == 0)
736              return NULL;
737
738          value += interval;
739     }
740 }
741
742 /**
743  * Initializes an asynchronous timer.
744  * @warning Asynchronous timers are processed from an unspecified thread.
745  * Also, multiple occurences of an interval timer can run concurrently.
746  *
747  * @param id pointer to timer to be initialized
748  * @param func function that the timer will call
749  * @param data parameter for the timer function
750  * @return 0 on success, a system error code otherwise.
751  */
752 int vlc_timer_create (vlc_timer_t *id, void (*func) (void *), void *data)
753 {
754     struct vlc_timer *timer = malloc (sizeof (*timer));
755
756     if (timer == NULL)
757         return ENOMEM;
758     vlc_mutex_init (&timer->lock);
759     vlc_cond_init (&timer->wait);
760     assert (func);
761     timer->func = func;
762     timer->data = data;
763     timer->value = 0;
764     timer->interval = 0;
765     timer->users = 0;
766     timer->overruns = 0;
767     *id = timer;
768     return 0;
769 }
770
771 /**
772  * Destroys an initialized timer. If needed, the timer is first disarmed.
773  * This function is undefined if the specified timer is not initialized.
774  *
775  * @warning This function <b>must</b> be called before the timer data can be
776  * freed and before the timer callback function can be unloaded.
777  *
778  * @param timer to destroy
779  */
780 void vlc_timer_destroy (vlc_timer_t *id)
781 {
782     struct vlc_timer *timer = *id;
783
784     vlc_timer_schedule (id, false, 0, 0);
785     vlc_mutex_lock (&timer->lock);
786     while (timer->users != 0)
787         vlc_cond_wait (&timer->wait, &timer->lock);
788     vlc_mutex_unlock (&timer->lock);
789
790     vlc_cond_destroy (&timer->wait);
791     vlc_mutex_destroy (&timer->lock);
792     free (timer);
793 }
794
795 /**
796  * Arm or disarm an initialized timer.
797  * This functions overrides any previous call to itself.
798  *
799  * @note A timer can fire later than requested due to system scheduling
800  * limitations. An interval timer can fail to trigger sometimes, either because
801  * the system is busy or suspended, or because a previous iteration of the
802  * timer is still running. See also vlc_timer_getoverrun().
803  *
804  * @param id initialized timer pointer
805  * @param absolute the timer value origin is the same as mdate() if true,
806  *                 the timer value is relative to now if false.
807  * @param value zero to disarm the timer, otherwise the initial time to wait
808  *              before firing the timer.
809  * @param interval zero to fire the timer just once, otherwise the timer
810  *                 repetition interval.
811  */
812 void vlc_timer_schedule (vlc_timer_t *id, bool absolute,
813                          mtime_t value, mtime_t interval)
814 {
815     struct vlc_timer *timer = *id;
816
817     vlc_mutex_lock (&timer->lock);
818     if (timer->value)
819     {
820         vlc_cancel (timer->thread);
821         vlc_join (timer->thread, NULL);
822         timer->value = 0;
823     }
824     if ((value != 0)
825      && (vlc_clone (&timer->thread, vlc_timer_thread, timer,
826                     VLC_THREAD_PRIORITY_INPUT) == 0))
827     {
828         timer->value = (absolute ? 0 : mdate ()) + value;
829         timer->interval = interval;
830     }
831     vlc_mutex_unlock (&timer->lock);
832 }
833
834 /**
835  * Fetch and reset the overrun counter for a timer.
836  * @param id initialized timer pointer
837  * @return the timer overrun counter, i.e. the number of times that the timer
838  * should have run but did not since the last actual run. If all is well, this
839  * is zero.
840  */
841 unsigned vlc_timer_getoverrun (const vlc_timer_t *id)
842 {
843     struct vlc_timer *timer = *id;
844     unsigned ret;
845
846     vlc_mutex_lock (&timer->lock);
847     ret = timer->overruns;
848     timer->overruns = 0;
849     vlc_mutex_unlock (&timer->lock);
850     return ret;
851 }