1 /*****************************************************************************
2 * threads.c : threads implementation for the VideoLAN client
3 *****************************************************************************
4 * Copyright (C) 1999-2008 the VideoLAN team
7 * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
8 * Samuel Hocevar <sam@zoy.org>
9 * Gildas Bazin <gbazin@netcourrier.com>
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26 *****************************************************************************/
32 #include <vlc_common.h>
42 #define VLC_THREADS_UNINITIALIZED 0
43 #define VLC_THREADS_PENDING 1
44 #define VLC_THREADS_ERROR 2
45 #define VLC_THREADS_READY 3
47 /*****************************************************************************
48 * Global mutex for lazy initialization of the threads system
49 *****************************************************************************/
50 static volatile unsigned i_initializations = 0;
52 #if defined( LIBVLC_USE_PTHREAD )
55 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
57 static vlc_threadvar_t cancel_key;
61 * Global process-wide VLC object.
62 * Contains inter-instance data, such as the module cache and global mutexes.
64 static libvlc_global_data_t *p_root;
66 libvlc_global_data_t *vlc_global( void )
68 assert( i_initializations > 0 );
72 #ifdef HAVE_EXECINFO_H
73 # include <execinfo.h>
77 * Print a backtrace to the standard error for debugging purpose.
79 void vlc_trace (const char *fn, const char *file, unsigned line)
81 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
82 fflush (stderr); /* needed before switch to low-level I/O */
85 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
86 backtrace_symbols_fd (stack, len, 2);
93 static inline unsigned long vlc_threadid (void)
95 #if defined(LIBVLC_USE_PTHREAD)
96 union { pthread_t th; unsigned long int i; } v = { };
97 v.th = pthread_self ();
100 #elif defined (WIN32)
101 return GetCurrentThreadId ();
109 /*****************************************************************************
110 * vlc_thread_fatal: Report an error from the threading layer
111 *****************************************************************************
112 * This is mostly meant for debugging.
113 *****************************************************************************/
114 void vlc_thread_fatal (const char *action, int error, const char *function,
115 const char *file, unsigned line)
117 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
118 action, error, vlc_threadid ());
119 vlc_trace (function, file, line);
121 /* Sometimes strerror_r() crashes too, so make sure we print an error
122 * message before we invoke it */
124 /* Avoid the strerror_r() prototype brain damage in glibc */
126 fprintf (stderr, " Error message: %m at:\n");
127 #elif !defined (WIN32)
131 switch (strerror_r (error, buf, sizeof (buf)))
136 case ERANGE: /* should never happen */
137 msg = "unknwon (too big to display)";
140 msg = "unknown (invalid error number)";
143 fprintf (stderr, " Error message: %s\n", msg);
151 * Per-thread cancellation data
153 #ifndef LIBVLC_USE_PTHREAD_CANCEL
154 typedef struct vlc_cancel_t
156 vlc_cleanup_t *cleaners;
161 # define VLC_CANCEL_INIT { NULL, true, false }
164 /*****************************************************************************
165 * vlc_threads_init: initialize threads system
166 *****************************************************************************
167 * This function requires lazy initialization of a global lock in order to
168 * keep the library really thread-safe. Some architectures don't support this
169 * and thus do not guarantee the complete reentrancy.
170 *****************************************************************************/
171 int vlc_threads_init( void )
173 int i_ret = VLC_SUCCESS;
175 /* If we have lazy mutex initialization, use it. Otherwise, we just
176 * hope nothing wrong happens. */
177 #if defined( LIBVLC_USE_PTHREAD )
178 pthread_mutex_lock( &once_mutex );
181 if( i_initializations == 0 )
183 p_root = vlc_custom_create( (vlc_object_t *)NULL, sizeof( *p_root ),
184 VLC_OBJECT_GENERIC, "root" );
191 /* We should be safe now. Do all the initialization stuff we want. */
192 #ifndef LIBVLC_USE_PTHREAD_CANCEL
193 vlc_threadvar_create( &cancel_key, free );
199 /* If we have lazy mutex initialization support, unlock the mutex.
200 * Otherwize, we are screwed. */
201 #if defined( LIBVLC_USE_PTHREAD )
202 pthread_mutex_unlock( &once_mutex );
208 /*****************************************************************************
209 * vlc_threads_end: stop threads system
210 *****************************************************************************
211 * FIXME: This function is far from being threadsafe.
212 *****************************************************************************/
213 void vlc_threads_end( void )
215 #if defined( LIBVLC_USE_PTHREAD )
216 pthread_mutex_lock( &once_mutex );
219 assert( i_initializations > 0 );
221 if( i_initializations == 1 )
223 vlc_object_release( p_root );
224 #ifndef LIBVLC_USE_PTHREAD
225 vlc_threadvar_delete( &cancel_key );
230 #if defined( LIBVLC_USE_PTHREAD )
231 pthread_mutex_unlock( &once_mutex );
235 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
236 /* This is not prototyped under glibc, though it exists. */
237 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
240 /*****************************************************************************
241 * vlc_mutex_init: initialize a mutex
242 *****************************************************************************/
243 int vlc_mutex_init( vlc_mutex_t *p_mutex )
245 #if defined( LIBVLC_USE_PTHREAD )
246 pthread_mutexattr_t attr;
249 pthread_mutexattr_init( &attr );
252 /* Create error-checking mutex to detect problems more easily. */
253 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
254 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
256 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
259 i_result = pthread_mutex_init( p_mutex, &attr );
260 pthread_mutexattr_destroy( &attr );
262 #elif defined( UNDER_CE )
263 InitializeCriticalSection( &p_mutex->csection );
266 #elif defined( WIN32 )
267 *p_mutex = CreateMutex( NULL, FALSE, NULL );
268 return (*p_mutex != NULL) ? 0 : ENOMEM;
273 /*****************************************************************************
274 * vlc_mutex_init: initialize a recursive mutex (Do not use)
275 *****************************************************************************/
276 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
278 #if defined( LIBVLC_USE_PTHREAD )
279 pthread_mutexattr_t attr;
282 pthread_mutexattr_init( &attr );
283 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
284 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
286 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
288 i_result = pthread_mutex_init( p_mutex, &attr );
289 pthread_mutexattr_destroy( &attr );
291 #elif defined( WIN32 )
292 /* Create mutex returns a recursive mutex */
293 *p_mutex = CreateMutex( 0, FALSE, 0 );
294 return (*p_mutex != NULL) ? 0 : ENOMEM;
296 # error Unimplemented!
301 /*****************************************************************************
302 * vlc_mutex_destroy: destroy a mutex, inner version
303 *****************************************************************************/
304 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
306 #if defined( LIBVLC_USE_PTHREAD )
307 int val = pthread_mutex_destroy( p_mutex );
308 VLC_THREAD_ASSERT ("destroying mutex");
310 #elif defined( UNDER_CE )
311 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
313 DeleteCriticalSection( &p_mutex->csection );
315 #elif defined( WIN32 )
316 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
318 CloseHandle( *p_mutex );
323 /*****************************************************************************
324 * vlc_cond_init: initialize a condition variable
325 *****************************************************************************/
326 int vlc_cond_init( vlc_cond_t *p_condvar )
328 #if defined( LIBVLC_USE_PTHREAD )
329 pthread_condattr_t attr;
332 ret = pthread_condattr_init (&attr);
336 # if !defined (_POSIX_CLOCK_SELECTION)
337 /* Fairly outdated POSIX support (that was defined in 2001) */
338 # define _POSIX_CLOCK_SELECTION (-1)
340 # if (_POSIX_CLOCK_SELECTION >= 0)
341 /* NOTE: This must be the same clock as the one in mtime.c */
342 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
345 ret = pthread_cond_init (p_condvar, &attr);
346 pthread_condattr_destroy (&attr);
349 #elif defined( UNDER_CE ) || defined( WIN32 )
350 /* Create an auto-reset event. */
351 *p_condvar = CreateEvent( NULL, /* no security */
352 FALSE, /* auto-reset event */
353 FALSE, /* start non-signaled */
354 NULL ); /* unnamed */
355 return *p_condvar ? 0 : ENOMEM;
360 /*****************************************************************************
361 * vlc_cond_destroy: destroy a condition, inner version
362 *****************************************************************************/
363 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
365 #if defined( LIBVLC_USE_PTHREAD )
366 int val = pthread_cond_destroy( p_condvar );
367 VLC_THREAD_ASSERT ("destroying condition");
369 #elif defined( UNDER_CE ) || defined( WIN32 )
370 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
372 CloseHandle( *p_condvar );
378 * Wakes up all threads (if any) waiting on a condition variable.
379 * @param p_cond condition variable
381 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
383 #if defined (LIBVLC_USE_PTHREAD)
384 pthread_cond_broadcast (p_condvar);
386 #elif defined (WIN32)
387 SetEvent (*p_condvar);
393 /*****************************************************************************
394 * vlc_tls_create: create a thread-local variable
395 *****************************************************************************/
396 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
400 #if defined( LIBVLC_USE_PTHREAD )
401 i_ret = pthread_key_create( p_tls, destr );
402 #elif defined( UNDER_CE )
404 #elif defined( WIN32 )
405 /* FIXME: remember/use the destr() callback and stop leaking whatever */
407 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
409 # error Unimplemented!
414 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
416 #if defined( LIBVLC_USE_PTHREAD )
417 pthread_key_delete (*p_tls);
418 #elif defined( UNDER_CE )
419 #elif defined( WIN32 )
422 # error Unimplemented!
426 #if defined (LIBVLC_USE_PTHREAD)
427 #elif defined (WIN32)
428 static unsigned __stdcall vlc_entry (void *data)
430 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
431 vlc_thread_t self = data;
433 vlc_threadvar_set (&cancel_key, &cancel_data);
434 self->data = self->entry (self->data);
440 * Creates and starts new thread.
442 * @param p_handle [OUT] pointer to write the handle of the created thread to
443 * @param entry entry point for the thread
444 * @param data data parameter given to the entry point
445 * @param priority thread priority value
446 * @return 0 on success, a standard error code on error.
448 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
453 #if defined( LIBVLC_USE_PTHREAD )
455 pthread_attr_init (&attr);
457 /* Block the signals that signals interface plugin handles.
458 * If the LibVLC caller wants to handle some signals by itself, it should
459 * block these before whenever invoking LibVLC. And it must obviously not
460 * start the VLC signals interface plugin.
462 * LibVLC will normally ignore any interruption caused by an asynchronous
463 * signal during a system call. But there may well be some buggy cases
464 * where it fails to handle EINTR (bug reports welcome). Some underlying
465 * libraries might also not handle EINTR properly.
471 sigdelset (&set, SIGHUP);
472 sigaddset (&set, SIGINT);
473 sigaddset (&set, SIGQUIT);
474 sigaddset (&set, SIGTERM);
476 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
477 pthread_sigmask (SIG_BLOCK, &set, &oldset);
480 struct sched_param sp = { .sched_priority = priority, };
483 if (sp.sched_priority <= 0)
484 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
486 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
488 pthread_attr_setschedpolicy (&attr, policy);
489 pthread_attr_setschedparam (&attr, &sp);
492 ret = pthread_create (p_handle, &attr, entry, data);
493 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
494 pthread_attr_destroy (&attr);
496 #elif defined( WIN32 ) || defined( UNDER_CE )
497 /* When using the MSVCRT C library you have to use the _beginthreadex
498 * function instead of CreateThread, otherwise you'll end up with
499 * memory leaks and the signal functions not working (see Microsoft
500 * Knowledge Base, article 104641) */
502 vlc_thread_t th = malloc (sizeof (*th));
509 #if defined( UNDER_CE )
510 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
512 hThread = (HANDLE)(uintptr_t)
513 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
518 /* Thread closes the handle when exiting, duplicate it here
519 * to be on the safe side when joining. */
520 if (!DuplicateHandle (GetCurrentProcess (), hThread,
521 GetCurrentProcess (), &th->handle, 0, FALSE,
522 DUPLICATE_SAME_ACCESS))
524 CloseHandle (hThread);
529 ResumeThread (hThread);
531 SetThreadPriority (hThread, priority);
547 /* APC procedure for thread cancellation */
548 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
551 vlc_control_cancel (VLC_DO_CANCEL);
556 * Marks a thread as cancelled. Next time the target thread reaches a
557 * cancellation point (while not having disabled cancellation), it will
558 * run its cancellation cleanup handler, the thread variable destructors, and
559 * terminate. vlc_join() must be used afterward regardless of a thread being
562 void vlc_cancel (vlc_thread_t thread_id)
564 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
565 pthread_cancel (thread_id);
566 #elif defined (WIN32)
567 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
569 # warning vlc_cancel is not implemented!
574 * Waits for a thread to complete (if needed), and destroys it.
575 * This is a cancellation point; in case of cancellation, the join does _not_
578 * @param handle thread handle
579 * @param p_result [OUT] pointer to write the thread return value or NULL
580 * @return 0 on success, a standard error code otherwise.
582 void vlc_join (vlc_thread_t handle, void **result)
584 #if defined( LIBVLC_USE_PTHREAD )
585 int val = pthread_join (handle, result);
587 vlc_thread_fatal ("joining thread", val, __func__, __FILE__, __LINE__);
589 #elif defined( UNDER_CE ) || defined( WIN32 )
592 while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
593 == WAIT_IO_COMPLETION);
595 CloseHandle (handle->handle);
597 *result = handle->data;
604 struct vlc_thread_boot
606 void * (*entry) (vlc_object_t *);
607 vlc_object_t *object;
610 static void *thread_entry (void *data)
612 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
613 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
616 msg_Dbg (obj, "thread started");
618 msg_Dbg (obj, "thread ended");
623 /*****************************************************************************
624 * vlc_thread_create: create a thread, inner version
625 *****************************************************************************
626 * Note that i_priority is only taken into account on platforms supporting
627 * userland real-time priority threads.
628 *****************************************************************************/
629 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
630 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
631 int i_priority, bool b_wait )
634 vlc_object_internals_t *p_priv = vlc_internals( p_this );
636 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
640 boot->object = p_this;
642 vlc_object_lock( p_this );
644 /* Make sure we don't re-create a thread if the object has already one */
645 assert( !p_priv->b_thread );
647 #if defined( LIBVLC_USE_PTHREAD )
649 if( config_GetInt( p_this, "rt-priority" ) > 0 )
652 /* Hack to avoid error msg */
653 if( config_GetType( p_this, "rt-offset" ) )
654 i_priority += config_GetInt( p_this, "rt-offset" );
658 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
663 msg_Dbg( p_this, "waiting for thread initialization" );
664 vlc_object_wait( p_this );
667 p_priv->b_thread = true;
668 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
669 (unsigned long)p_priv->thread_id, psz_name, i_priority,
675 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
676 psz_name, psz_file, i_line );
679 vlc_object_unlock( p_this );
683 /*****************************************************************************
684 * vlc_thread_set_priority: set the priority of the current thread when we
685 * couldn't set it in vlc_thread_create (for instance for the main thread)
686 *****************************************************************************/
687 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
688 int i_line, int i_priority )
690 vlc_object_internals_t *p_priv = vlc_internals( p_this );
692 if( !p_priv->b_thread )
694 msg_Err( p_this, "couldn't set priority of non-existent thread" );
698 #if defined( LIBVLC_USE_PTHREAD )
700 if( config_GetInt( p_this, "rt-priority" ) > 0 )
703 int i_error, i_policy;
704 struct sched_param param;
706 memset( ¶m, 0, sizeof(struct sched_param) );
707 if( config_GetType( p_this, "rt-offset" ) )
708 i_priority += config_GetInt( p_this, "rt-offset" );
709 if( i_priority <= 0 )
711 param.sched_priority = (-1) * i_priority;
712 i_policy = SCHED_OTHER;
716 param.sched_priority = i_priority;
719 if( (i_error = pthread_setschedparam( p_priv->thread_id,
720 i_policy, ¶m )) )
723 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
729 #elif defined( WIN32 ) || defined( UNDER_CE )
730 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
732 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
734 msg_Warn( p_this, "couldn't set a faster priority" );
743 /*****************************************************************************
744 * vlc_thread_join: wait until a thread exits, inner version
745 *****************************************************************************/
746 void __vlc_thread_join( vlc_object_t *p_this )
748 vlc_object_internals_t *p_priv = vlc_internals( p_this );
750 #if defined( LIBVLC_USE_PTHREAD )
751 vlc_join (p_priv->thread_id, NULL);
753 #elif defined( UNDER_CE ) || defined( WIN32 )
755 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
756 int64_t real_time, kernel_time, user_time;
758 if( ! DuplicateHandle(GetCurrentProcess(),
759 p_priv->thread_id->handle,
764 DUPLICATE_SAME_ACCESS) )
766 p_priv->b_thread = false;
767 return; /* We have a problem! */
770 vlc_join( p_priv->thread_id, NULL );
772 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
775 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
776 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
780 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
781 kernel_ft.dwLowDateTime) / 10;
784 ((((int64_t)user_ft.dwHighDateTime)<<32)|
785 user_ft.dwLowDateTime) / 10;
787 msg_Dbg( p_this, "thread times: "
788 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
789 real_time/60/1000000,
790 (double)((real_time%(60*1000000))/1000000.0),
791 kernel_time/60/1000000,
792 (double)((kernel_time%(60*1000000))/1000000.0),
793 user_time/60/1000000,
794 (double)((user_time%(60*1000000))/1000000.0) );
796 CloseHandle( hThread );
799 vlc_join( p_priv->thread_id, NULL );
803 p_priv->b_thread = false;
806 void vlc_thread_cancel (vlc_object_t *obj)
808 vlc_object_internals_t *priv = vlc_internals (obj);
811 vlc_cancel (priv->thread_id);
814 void vlc_control_cancel (int cmd, ...)
816 /* NOTE: This function only modifies thread-specific data, so there is no
817 * need to lock anything. */
818 #ifdef LIBVLC_USE_PTHREAD_CANCEL
824 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
828 /* Main thread - cannot be cancelled anyway */
831 nfo = malloc (sizeof (*nfo));
833 return; /* Uho! Expect problems! */
834 *nfo = VLC_CANCEL_INIT;
835 vlc_threadvar_set (&cancel_key, nfo);
842 case VLC_SAVE_CANCEL:
844 int *p_state = va_arg (ap, int *);
845 *p_state = nfo->killable;
846 nfo->killable = false;
850 case VLC_RESTORE_CANCEL:
852 int state = va_arg (ap, int);
853 nfo->killable = state != 0;
857 case VLC_TEST_CANCEL:
858 if (nfo->killable && nfo->killed)
860 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
863 #if defined (LIBVLC_USE_PTHREAD)
864 pthread_exit (PTHREAD_CANCELLED);
865 #elif defined (WIN32)
868 # error Not implemented!
877 case VLC_CLEANUP_PUSH:
879 /* cleaner is a pointer to the caller stack, no need to allocate
880 * and copy anything. As a nice side effect, this cannot fail. */
881 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
882 cleaner->next = nfo->cleaners;
883 nfo->cleaners = cleaner;
887 case VLC_CLEANUP_POP:
889 nfo->cleaners = nfo->cleaners->next;