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() */
41 # include <sys/syscall.h> /* SYS_gettid */
44 #ifdef HAVE_EXECINFO_H
45 # include <execinfo.h>
49 # include <sys/time.h> /* gettimeofday in vlc_cond_timedwait */
53 * Print a backtrace to the standard error for debugging purpose.
55 void vlc_trace (const char *fn, const char *file, unsigned line)
57 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
58 fflush (stderr); /* needed before switch to low-level I/O */
61 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
62 backtrace_symbols_fd (stack, len, 2);
67 static inline unsigned long vlc_threadid (void)
69 #if defined (__linux__)
70 /* glibc does not provide a call for this */
71 return syscall (SYS_gettid);
74 union { pthread_t th; unsigned long int i; } v = { };
75 v.th = pthread_self ();
82 /*****************************************************************************
83 * vlc_thread_fatal: Report an error from the threading layer
84 *****************************************************************************
85 * This is mostly meant for debugging.
86 *****************************************************************************/
88 vlc_thread_fatal (const char *action, int error,
89 const char *function, const char *file, unsigned line)
91 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
92 action, error, vlc_threadid ());
93 vlc_trace (function, file, line);
95 /* Sometimes strerror_r() crashes too, so make sure we print an error
96 * message before we invoke it */
98 /* Avoid the strerror_r() prototype brain damage in glibc */
100 fprintf (stderr, " Error message: %m\n");
105 switch (strerror_r (error, buf, sizeof (buf)))
110 case ERANGE: /* should never happen */
111 msg = "unknwon (too big to display)";
114 msg = "unknown (invalid error number)";
117 fprintf (stderr, " Error message: %s\n", msg);
124 # define VLC_THREAD_ASSERT( action ) \
125 if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
127 # define VLC_THREAD_ASSERT( action ) ((void)val)
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 );
135 /*****************************************************************************
136 * vlc_mutex_init: initialize a mutex
137 *****************************************************************************/
138 void vlc_mutex_init( vlc_mutex_t *p_mutex )
140 pthread_mutexattr_t attr;
142 if( pthread_mutexattr_init( &attr ) )
145 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_NORMAL );
147 /* Create error-checking mutex to detect problems more easily. */
148 # if defined (__GLIBC__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 6)
149 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
151 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
154 if( pthread_mutex_init( p_mutex, &attr ) )
156 pthread_mutexattr_destroy( &attr );
159 /*****************************************************************************
160 * vlc_mutex_init: initialize a recursive mutex (Do not use)
161 *****************************************************************************/
162 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
164 pthread_mutexattr_t attr;
166 pthread_mutexattr_init( &attr );
167 #if defined (__GLIBC__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 6)
168 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
170 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
172 if( pthread_mutex_init( p_mutex, &attr ) )
174 pthread_mutexattr_destroy( &attr );
179 * Destroys a mutex. The mutex must not be locked.
181 * @param p_mutex mutex to destroy
182 * @return always succeeds
184 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
186 int val = pthread_mutex_destroy( p_mutex );
187 VLC_THREAD_ASSERT ("destroying mutex");
191 # ifdef HAVE_VALGRIND_VALGRIND_H
192 # include <valgrind/valgrind.h>
194 # define RUNNING_ON_VALGRIND (0)
197 void vlc_assert_locked (vlc_mutex_t *p_mutex)
199 if (RUNNING_ON_VALGRIND > 0)
201 assert (pthread_mutex_lock (p_mutex) == EDEADLK);
206 * Acquires a mutex. If needed, waits for any other thread to release it.
207 * Beware of deadlocks when locking multiple mutexes at the same time,
208 * or when using mutexes from callbacks.
209 * This function is not a cancellation-point.
211 * @param p_mutex mutex initialized with vlc_mutex_init() or
212 * vlc_mutex_init_recursive()
214 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
216 int val = pthread_mutex_lock( p_mutex );
217 VLC_THREAD_ASSERT ("locking mutex");
221 * Acquires a mutex if and only if it is not currently held by another thread.
222 * This function never sleeps and can be used in delay-critical code paths.
223 * This function is not a cancellation-point.
225 * <b>Beware</b>: If this function fails, then the mutex is held... by another
226 * thread. The calling thread must deal with the error appropriately. That
227 * typically implies postponing the operations that would have required the
228 * mutex. If the thread cannot defer those operations, then it must use
229 * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
231 * @param p_mutex mutex initialized with vlc_mutex_init() or
232 * vlc_mutex_init_recursive()
233 * @return 0 if the mutex could be acquired, an error code otherwise.
235 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
237 int val = pthread_mutex_trylock( p_mutex );
240 VLC_THREAD_ASSERT ("locking mutex");
245 * Releases a mutex (or crashes if the mutex is not locked by the caller).
246 * @param p_mutex mutex locked with vlc_mutex_lock().
248 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
250 int val = pthread_mutex_unlock( p_mutex );
251 VLC_THREAD_ASSERT ("unlocking mutex");
254 /*****************************************************************************
255 * vlc_cond_init: initialize a condition variable
256 *****************************************************************************/
257 void vlc_cond_init( vlc_cond_t *p_condvar )
259 pthread_condattr_t attr;
261 if (pthread_condattr_init (&attr))
263 #if !defined (_POSIX_CLOCK_SELECTION)
264 /* Fairly outdated POSIX support (that was defined in 2001) */
265 # define _POSIX_CLOCK_SELECTION (-1)
267 #if (_POSIX_CLOCK_SELECTION >= 0)
268 /* NOTE: This must be the same clock as the one in mtime.c */
269 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
272 if (pthread_cond_init (p_condvar, &attr))
274 pthread_condattr_destroy (&attr);
278 * Destroys a condition variable. No threads shall be waiting or signaling the
280 * @param p_condvar condition variable to destroy
282 void vlc_cond_destroy (vlc_cond_t *p_condvar)
284 int val = pthread_cond_destroy( p_condvar );
285 VLC_THREAD_ASSERT ("destroying condition");
289 * Wakes up one thread waiting on a condition variable, if any.
290 * @param p_condvar condition variable
292 void vlc_cond_signal (vlc_cond_t *p_condvar)
294 int val = pthread_cond_signal( p_condvar );
295 VLC_THREAD_ASSERT ("signaling condition variable");
299 * Wakes up all threads (if any) waiting on a condition variable.
300 * @param p_cond condition variable
302 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
304 pthread_cond_broadcast (p_condvar);
308 * Waits for a condition variable. The calling thread will be suspended until
309 * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
310 * condition variable, the thread is cancelled with vlc_cancel(), or the
311 * system causes a "spurious" unsolicited wake-up.
313 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
314 * a recursive mutex. Although it is possible to use the same mutex for
315 * multiple condition, it is not valid to use different mutexes for the same
316 * condition variable at the same time from different threads.
318 * In case of thread cancellation, the mutex is always locked before
319 * cancellation proceeds.
321 * The canonical way to use a condition variable to wait for event foobar is:
323 vlc_mutex_lock (&lock);
324 mutex_cleanup_push (&lock); // release the mutex in case of cancellation
327 vlc_cond_wait (&wait, &lock);
329 --- foobar is now true, do something about it here --
331 vlc_cleanup_run (); // release the mutex
334 * @param p_condvar condition variable to wait on
335 * @param p_mutex mutex which is unlocked while waiting,
336 * then locked again when waking up.
337 * @param deadline <b>absolute</b> timeout
339 * @return 0 if the condition was signaled, an error code in case of timeout.
341 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
343 int val = pthread_cond_wait( p_condvar, p_mutex );
344 VLC_THREAD_ASSERT ("waiting on condition");
348 * Waits for a condition variable up to a certain date.
349 * This works like vlc_cond_wait(), except for the additional timeout.
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 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
361 #if defined(__APPLE__) && !defined(__powerpc__) && !defined( __ppc__ ) && !defined( __ppc64__ )
362 /* mdate() is mac_absolute_time on OSX, which we must convert to do
363 * the same base than gettimeofday() which pthread_cond_timedwait
365 mtime_t oldbase = mdate();
367 gettimeofday(&tv, NULL);
368 mtime_t newbase = (mtime_t)tv.tv_sec * 1000000 + (mtime_t) tv.tv_usec;
369 deadline = deadline - oldbase + newbase;
371 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
372 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
374 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
375 if (val != ETIMEDOUT)
376 VLC_THREAD_ASSERT ("timed-waiting on condition");
381 * Initializes a read/write lock.
383 void vlc_rwlock_init (vlc_rwlock_t *lock)
385 if (pthread_rwlock_init (lock, NULL))
390 * Destroys an initialized unused read/write lock.
392 void vlc_rwlock_destroy (vlc_rwlock_t *lock)
394 int val = pthread_rwlock_destroy (lock);
395 VLC_THREAD_ASSERT ("destroying R/W lock");
399 * Acquires a read/write lock for reading. Recursion is allowed.
401 void vlc_rwlock_rdlock (vlc_rwlock_t *lock)
403 int val = pthread_rwlock_rdlock (lock);
404 VLC_THREAD_ASSERT ("acquiring R/W lock for reading");
408 * Acquires a read/write lock for writing. Recursion is not allowed.
410 void vlc_rwlock_wrlock (vlc_rwlock_t *lock)
412 int val = pthread_rwlock_wrlock (lock);
413 VLC_THREAD_ASSERT ("acquiring R/W lock for writing");
417 * Releases a read/write lock.
419 void vlc_rwlock_unlock (vlc_rwlock_t *lock)
421 int val = pthread_rwlock_unlock (lock);
422 VLC_THREAD_ASSERT ("releasing R/W lock");
426 * Allocates a thread-specific variable.
427 * @param key where to store the thread-specific variable handle
428 * @param destr a destruction callback. It is called whenever a thread exits
429 * and the thread-specific variable has a non-NULL value.
430 * @return 0 on success, a system error code otherwise. This function can
431 * actually fail because there is a fixed limit on the number of
432 * thread-specific variable in a process on most systems.
434 int vlc_threadvar_create (vlc_threadvar_t *key, void (*destr) (void *))
436 return pthread_key_create (key, destr);
439 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
441 pthread_key_delete (*p_tls);
445 * Sets a thread-specific variable.
446 * @param key thread-local variable key (created with vlc_threadvar_create())
447 * @param value new value for the variable for the calling thread
448 * @return 0 on success, a system error code otherwise.
450 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
452 return pthread_setspecific (key, value);
456 * Gets the value of a thread-local variable for the calling thread.
457 * This function cannot fail.
458 * @return the value associated with the given variable for the calling
459 * or NULL if there is no value.
461 void *vlc_threadvar_get (vlc_threadvar_t key)
463 return pthread_getspecific (key);
466 static bool rt_priorities = false;
467 static int rt_offset;
469 void vlc_threads_setup (libvlc_int_t *p_libvlc)
471 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
472 static bool initialized = false;
474 vlc_mutex_lock (&lock);
475 /* Initializes real-time priorities before any thread is created,
476 * just once per process. */
480 if (config_GetInt (p_libvlc, "rt-priority"))
483 rt_offset = config_GetInt (p_libvlc, "rt-offset");
484 rt_priorities = true;
488 vlc_mutex_unlock (&lock);
492 * Creates and starts new thread.
494 * @param p_handle [OUT] pointer to write the handle of the created thread to
495 * @param entry entry point for the thread
496 * @param data data parameter given to the entry point
497 * @param priority thread priority value
498 * @return 0 on success, a standard error code on error.
500 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
506 pthread_attr_init (&attr);
508 /* Block the signals that signals interface plugin handles.
509 * If the LibVLC caller wants to handle some signals by itself, it should
510 * block these before whenever invoking LibVLC. And it must obviously not
511 * start the VLC signals interface plugin.
513 * LibVLC will normally ignore any interruption caused by an asynchronous
514 * signal during a system call. But there may well be some buggy cases
515 * where it fails to handle EINTR (bug reports welcome). Some underlying
516 * libraries might also not handle EINTR properly.
522 sigdelset (&set, SIGHUP);
523 sigaddset (&set, SIGINT);
524 sigaddset (&set, SIGQUIT);
525 sigaddset (&set, SIGTERM);
527 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
528 pthread_sigmask (SIG_BLOCK, &set, &oldset);
531 #if defined (_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING >= 0) \
532 && defined (_POSIX_THREAD_PRIORITY_SCHEDULING) \
533 && (_POSIX_THREAD_PRIORITY_SCHEDULING >= 0)
536 struct sched_param sp = { .sched_priority = priority + rt_offset, };
539 if (sp.sched_priority <= 0)
540 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
542 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
544 pthread_attr_setschedpolicy (&attr, policy);
545 pthread_attr_setschedparam (&attr, &sp);
551 /* The thread stack size.
552 * The lower the value, the less address space per thread, the highest
553 * maximum simultaneous threads per process. Too low values will cause
554 * stack overflows and weird crashes. Set with caution. Also keep in mind
555 * that 64-bits platforms consume more stack than 32-bits one.
557 * Thanks to on-demand paging, thread stack size only affects address space
558 * consumption. In terms of memory, threads only use what they need
559 * (rounded up to the page boundary).
561 * For example, on Linux i386, the default is 2 mega-bytes, which supports
562 * about 320 threads per processes. */
563 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
566 ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
567 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
570 ret = pthread_create (p_handle, &attr, entry, data);
571 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
572 pthread_attr_destroy (&attr);
577 * Marks a thread as cancelled. Next time the target thread reaches a
578 * cancellation point (while not having disabled cancellation), it will
579 * run its cancellation cleanup handler, the thread variable destructors, and
580 * terminate. vlc_join() must be used afterward regardless of a thread being
583 void vlc_cancel (vlc_thread_t thread_id)
585 pthread_cancel (thread_id);
589 * Waits for a thread to complete (if needed), then destroys it.
590 * This is a cancellation point; in case of cancellation, the join does _not_
593 * A thread cannot join itself (normally VLC will abort if this is attempted).
594 * Also, a detached thread <b>cannot</b> be joined.
596 * @param handle thread handle
597 * @param p_result [OUT] pointer to write the thread return value or NULL
599 void vlc_join (vlc_thread_t handle, void **result)
601 int val = pthread_join (handle, result);
602 VLC_THREAD_ASSERT ("joining thread");
606 * Detaches a thread. When the specified thread completes, it will be
607 * automatically destroyed (in particular, its stack will be reclaimed),
608 * instead of waiting for another thread to call vlc_join(). If the thread has
609 * already completed, it will be destroyed immediately.
611 * When a thread performs some work asynchronously and may complete much
612 * earlier than it can be joined, detaching the thread can save memory.
613 * However, care must be taken that any resources used by a detached thread
614 * remains valid until the thread completes. This will typically involve some
615 * kind of thread-safe signaling.
617 * A thread may detach itself.
619 * @param handle thread handle
621 void vlc_detach (vlc_thread_t handle)
623 int val = pthread_detach (handle);
624 VLC_THREAD_ASSERT ("detaching thread");
628 * Save the current cancellation state (enabled or disabled), then disable
629 * cancellation for the calling thread.
630 * This function must be called before entering a piece of code that is not
631 * cancellation-safe, unless it can be proven that the calling thread will not
633 * @return Previous cancellation state (opaque value for vlc_restorecancel()).
635 int vlc_savecancel (void)
638 int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
640 VLC_THREAD_ASSERT ("saving cancellation");
645 * Restore the cancellation state for the calling thread.
646 * @param state previous state as returned by vlc_savecancel().
647 * @return Nothing, always succeeds.
649 void vlc_restorecancel (int state)
654 val = pthread_setcancelstate (state, &oldstate);
655 /* This should fail if an invalid value for given for state */
656 VLC_THREAD_ASSERT ("restoring cancellation");
658 if (oldstate != PTHREAD_CANCEL_DISABLE)
659 vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
660 __func__, __FILE__, __LINE__);
662 pthread_setcancelstate (state, NULL);
667 * Issues an explicit deferred cancellation point.
668 * This has no effect if thread cancellation is disabled.
669 * This can be called when there is a rather slow non-sleeping operation.
670 * This is also used to force a cancellation point in a function that would
671 * otherwise "not always" be a one (block_FifoGet() is an example).
673 void vlc_testcancel (void)
675 pthread_testcancel ();
678 void vlc_control_cancel (int cmd, ...)
690 void (*func) (void *);
692 mtime_t value, interval;
697 static void *vlc_timer_do (void *data)
699 struct vlc_timer *timer = data;
701 timer->func (timer->data);
703 vlc_mutex_lock (&timer->lock);
704 assert (timer->users > 0);
705 if (--timer->users == 0)
706 vlc_cond_signal (&timer->wait);
707 vlc_mutex_unlock (&timer->lock);
711 static void *vlc_timer_thread (void *data)
713 struct vlc_timer *timer = data;
714 mtime_t value, interval;
716 vlc_mutex_lock (&timer->lock);
717 value = timer->value;
718 interval = timer->interval;
719 vlc_mutex_unlock (&timer->lock);
727 vlc_mutex_lock (&timer->lock);
728 if (vlc_clone (&th, vlc_timer_do, timer, VLC_THREAD_PRIORITY_INPUT))
735 vlc_mutex_unlock (&timer->lock);
745 * Initializes an asynchronous timer.
746 * @warning Asynchronous timers are processed from an unspecified thread.
747 * Also, multiple occurences of an interval timer can run concurrently.
749 * @param id pointer to timer to be initialized
750 * @param func function that the timer will call
751 * @param data parameter for the timer function
752 * @return 0 on success, a system error code otherwise.
754 int vlc_timer_create (vlc_timer_t *id, void (*func) (void *), void *data)
756 struct vlc_timer *timer = malloc (sizeof (*timer));
760 vlc_mutex_init (&timer->lock);
761 vlc_cond_init (&timer->wait);
774 * Destroys an initialized timer. If needed, the timer is first disarmed.
775 * This function is undefined if the specified timer is not initialized.
777 * @warning This function <b>must</b> be called before the timer data can be
778 * freed and before the timer callback function can be unloaded.
780 * @param timer timer to destroy
782 void vlc_timer_destroy (vlc_timer_t timer)
784 vlc_timer_schedule (timer, 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);
790 vlc_cond_destroy (&timer->wait);
791 vlc_mutex_destroy (&timer->lock);
796 * Arm or disarm an initialized timer.
797 * This functions overrides any previous call to itself.
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().
804 * @param timer initialized timer
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.
812 void vlc_timer_schedule (vlc_timer_t timer, bool absolute,
813 mtime_t value, mtime_t interval)
815 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
817 vlc_mutex_lock (&lock);
818 vlc_mutex_lock (&timer->lock);
821 vlc_mutex_unlock (&timer->lock);
822 vlc_cancel (timer->thread);
823 vlc_join (timer->thread, NULL);
824 vlc_mutex_lock (&timer->lock);
828 && (vlc_clone (&timer->thread, vlc_timer_thread, timer,
829 VLC_THREAD_PRIORITY_INPUT) == 0))
831 timer->value = (absolute ? 0 : mdate ()) + value;
832 timer->interval = interval;
834 vlc_mutex_unlock (&timer->lock);
835 vlc_mutex_unlock (&lock);
839 * Fetch and reset the overrun counter for a timer.
840 * @param timer initialized timer
841 * @return the timer overrun counter, i.e. the number of times that the timer
842 * should have run but did not since the last actual run. If all is well, this
845 unsigned vlc_timer_getoverrun (vlc_timer_t timer)
849 vlc_mutex_lock (&timer->lock);
850 ret = timer->overruns;
852 vlc_mutex_unlock (&timer->lock);