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>
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>
41 #define VLC_THREADS_UNINITIALIZED 0
42 #define VLC_THREADS_PENDING 1
43 #define VLC_THREADS_ERROR 2
44 #define VLC_THREADS_READY 3
46 /*****************************************************************************
47 * Global mutex for lazy initialization of the threads system
48 *****************************************************************************/
49 static volatile unsigned i_initializations = 0;
51 #if defined( LIBVLC_USE_PTHREAD )
54 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
58 * Global process-wide VLC object.
59 * Contains inter-instance data, such as the module cache and global mutexes.
61 static libvlc_global_data_t *p_root;
63 libvlc_global_data_t *vlc_global( void )
65 assert( i_initializations > 0 );
69 #if defined(LIBVLC_USE_PTHREAD)
70 static inline unsigned long vlc_threadid (void)
72 union { pthread_t th; unsigned long int i; } v = { };
73 v.th = pthread_self ();
77 #if defined(HAVE_EXECINFO_H) && defined(HAVE_BACKTRACE)
78 # include <execinfo.h>
81 /*****************************************************************************
82 * vlc_thread_fatal: Report an error from the threading layer
83 *****************************************************************************
84 * This is mostly meant for debugging.
85 *****************************************************************************/
86 void vlc_pthread_fatal (const char *action, int error,
87 const char *file, unsigned line)
89 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
90 action, vlc_threadid (), file, line, error);
92 /* Sometimes strerror_r() crashes too, so make sure we print an error
93 * message before we invoke it */
95 /* Avoid the strerror_r() prototype brain damage in glibc */
97 fprintf (stderr, " Error message: %m at:\n");
102 switch (strerror_r (error, buf, sizeof (buf)))
107 case ERANGE: /* should never happen */
108 msg = "unknwon (too big to display)";
111 msg = "unknown (invalid error number)";
114 fprintf (stderr, " Error message: %s\n", msg);
118 #ifdef HAVE_BACKTRACE
120 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
121 backtrace_symbols_fd (stack, len, 2);
127 void vlc_pthread_fatal (const char *action, int error,
128 const char *file, unsigned line)
130 (void)action; (void)error; (void)file; (void)line;
134 static vlc_threadvar_t cancel_key;
138 * Per-thread cancellation data
140 #ifndef LIBVLC_USE_PTHREAD_CANCEL
141 typedef struct vlc_cancel_t
143 vlc_cleanup_t *cleaners;
148 # define VLC_CANCEL_INIT { NULL, false, true }
151 /*****************************************************************************
152 * vlc_threads_init: initialize threads system
153 *****************************************************************************
154 * This function requires lazy initialization of a global lock in order to
155 * keep the library really thread-safe. Some architectures don't support this
156 * and thus do not guarantee the complete reentrancy.
157 *****************************************************************************/
158 int vlc_threads_init( void )
160 int i_ret = VLC_SUCCESS;
162 /* If we have lazy mutex initialization, use it. Otherwise, we just
163 * hope nothing wrong happens. */
164 #if defined( LIBVLC_USE_PTHREAD )
165 pthread_mutex_lock( &once_mutex );
168 if( i_initializations == 0 )
170 p_root = vlc_custom_create( (vlc_object_t *)NULL, sizeof( *p_root ),
171 VLC_OBJECT_GENERIC, "root" );
178 /* We should be safe now. Do all the initialization stuff we want. */
179 #ifndef LIBVLC_USE_PTHREAD_CANCEL
180 vlc_threadvar_create( &cancel_key, free );
186 /* If we have lazy mutex initialization support, unlock the mutex.
187 * Otherwize, we are screwed. */
188 #if defined( LIBVLC_USE_PTHREAD )
189 pthread_mutex_unlock( &once_mutex );
195 /*****************************************************************************
196 * vlc_threads_end: stop threads system
197 *****************************************************************************
198 * FIXME: This function is far from being threadsafe.
199 *****************************************************************************/
200 void vlc_threads_end( void )
202 #if defined( LIBVLC_USE_PTHREAD )
203 pthread_mutex_lock( &once_mutex );
206 assert( i_initializations > 0 );
208 if( i_initializations == 1 )
210 vlc_object_release( p_root );
211 #ifndef LIBVLC_USE_PTHREAD
212 vlc_threadvar_delete( &cancel_key );
217 #if defined( LIBVLC_USE_PTHREAD )
218 pthread_mutex_unlock( &once_mutex );
222 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
223 /* This is not prototyped under glibc, though it exists. */
224 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
227 /*****************************************************************************
228 * vlc_mutex_init: initialize a mutex
229 *****************************************************************************/
230 int vlc_mutex_init( vlc_mutex_t *p_mutex )
232 #if defined( LIBVLC_USE_PTHREAD )
233 pthread_mutexattr_t attr;
236 pthread_mutexattr_init( &attr );
239 /* Create error-checking mutex to detect problems more easily. */
240 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
241 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
243 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
246 i_result = pthread_mutex_init( p_mutex, &attr );
247 pthread_mutexattr_destroy( &attr );
249 #elif defined( UNDER_CE )
250 InitializeCriticalSection( &p_mutex->csection );
253 #elif defined( WIN32 )
254 *p_mutex = CreateMutex( 0, FALSE, 0 );
255 return (*p_mutex != NULL) ? 0 : ENOMEM;
257 #elif defined( HAVE_KERNEL_SCHEDULER_H )
258 /* check the arguments and whether it's already been initialized */
259 if( p_mutex == NULL )
264 if( p_mutex->init == 9999 )
269 p_mutex->lock = create_sem( 1, "BeMutex" );
270 if( p_mutex->lock < B_NO_ERROR )
275 p_mutex->init = 9999;
281 /*****************************************************************************
282 * vlc_mutex_init: initialize a recursive mutex (Do not use)
283 *****************************************************************************/
284 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
286 #if defined( LIBVLC_USE_PTHREAD )
287 pthread_mutexattr_t attr;
290 pthread_mutexattr_init( &attr );
291 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
292 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
294 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
296 i_result = pthread_mutex_init( p_mutex, &attr );
297 pthread_mutexattr_destroy( &attr );
299 #elif defined( WIN32 )
300 /* Create mutex returns a recursive mutex */
301 *p_mutex = CreateMutex( 0, FALSE, 0 );
302 return (*p_mutex != NULL) ? 0 : ENOMEM;
304 # error Unimplemented!
309 /*****************************************************************************
310 * vlc_mutex_destroy: destroy a mutex, inner version
311 *****************************************************************************/
312 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
314 #if defined( LIBVLC_USE_PTHREAD )
315 int val = pthread_mutex_destroy( p_mutex );
316 VLC_THREAD_ASSERT ("destroying mutex");
318 #elif defined( UNDER_CE )
319 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
321 DeleteCriticalSection( &p_mutex->csection );
323 #elif defined( WIN32 )
324 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
326 CloseHandle( *p_mutex );
328 #elif defined( HAVE_KERNEL_SCHEDULER_H )
329 if( p_mutex->init == 9999 )
330 delete_sem( p_mutex->lock );
337 /*****************************************************************************
338 * vlc_cond_init: initialize a condition
339 *****************************************************************************/
340 int __vlc_cond_init( vlc_cond_t *p_condvar )
342 #if defined( LIBVLC_USE_PTHREAD )
343 pthread_condattr_t attr;
346 ret = pthread_condattr_init (&attr);
350 # if !defined (_POSIX_CLOCK_SELECTION)
351 /* Fairly outdated POSIX support (that was defined in 2001) */
352 # define _POSIX_CLOCK_SELECTION (-1)
354 # if (_POSIX_CLOCK_SELECTION >= 0)
355 /* NOTE: This must be the same clock as the one in mtime.c */
356 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
359 ret = pthread_cond_init (p_condvar, &attr);
360 pthread_condattr_destroy (&attr);
363 #elif defined( UNDER_CE ) || defined( WIN32 )
364 /* Create an auto-reset event. */
365 *p_condvar = CreateEvent( NULL, /* no security */
366 FALSE, /* auto-reset event */
367 FALSE, /* start non-signaled */
368 NULL ); /* unnamed */
369 return *p_condvar ? 0 : ENOMEM;
371 #elif defined( HAVE_KERNEL_SCHEDULER_H )
377 if( p_condvar->init == 9999 )
382 p_condvar->thread = -1;
383 p_condvar->init = 9999;
389 /*****************************************************************************
390 * vlc_cond_destroy: destroy a condition, inner version
391 *****************************************************************************/
392 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
394 #if defined( LIBVLC_USE_PTHREAD )
395 int val = pthread_cond_destroy( p_condvar );
396 VLC_THREAD_ASSERT ("destroying condition");
398 #elif defined( UNDER_CE ) || defined( WIN32 )
399 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
401 CloseHandle( *p_condvar );
403 #elif defined( HAVE_KERNEL_SCHEDULER_H )
409 /*****************************************************************************
410 * vlc_tls_create: create a thread-local variable
411 *****************************************************************************/
412 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
416 #if defined( LIBVLC_USE_PTHREAD )
417 i_ret = pthread_key_create( p_tls, destr );
418 #elif defined( UNDER_CE )
420 #elif defined( WIN32 )
421 /* FIXME: remember/use the destr() callback and stop leaking whatever */
423 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
425 # error Unimplemented!
430 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
432 #if defined( LIBVLC_USE_PTHREAD )
433 pthread_key_delete (*p_tls);
434 #elif defined( UNDER_CE )
435 #elif defined( WIN32 )
438 # error Unimplemented!
442 #if defined (LIBVLC_USE_PTHREAD)
443 #elif defined (WIN32)
444 static unsigned __stdcall vlc_entry (void *data)
446 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
447 vlc_thread_t self = data;
449 vlc_threadvar_set (&cancel_key, &cancel_data);
450 self->data = self->entry (self->data);
456 * Creates and starts new thread.
458 * @param p_handle [OUT] pointer to write the handle of the created thread to
459 * @param entry entry point for the thread
460 * @param data data parameter given to the entry point
461 * @param priority thread priority value
462 * @return 0 on success, a standard error code on error.
464 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
469 #if defined( LIBVLC_USE_PTHREAD )
471 pthread_attr_init (&attr);
473 /* Block the signals that signals interface plugin handles.
474 * If the LibVLC caller wants to handle some signals by itself, it should
475 * block these before whenever invoking LibVLC. And it must obviously not
476 * start the VLC signals interface plugin.
478 * LibVLC will normally ignore any interruption caused by an asynchronous
479 * signal during a system call. But there may well be some buggy cases
480 * where it fails to handle EINTR (bug reports welcome). Some underlying
481 * libraries might also not handle EINTR properly.
487 sigdelset (&set, SIGHUP);
488 sigaddset (&set, SIGINT);
489 sigaddset (&set, SIGQUIT);
490 sigaddset (&set, SIGTERM);
492 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
493 pthread_sigmask (SIG_BLOCK, &set, &oldset);
496 struct sched_param sp = { .sched_priority = priority, };
499 if (sp.sched_priority <= 0)
500 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
502 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
504 pthread_attr_setschedpolicy (&attr, policy);
505 pthread_attr_setschedparam (&attr, &sp);
508 ret = pthread_create (p_handle, &attr, entry, data);
509 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
510 pthread_attr_destroy (&attr);
512 #elif defined( WIN32 ) || defined( UNDER_CE )
513 /* When using the MSVCRT C library you have to use the _beginthreadex
514 * function instead of CreateThread, otherwise you'll end up with
515 * memory leaks and the signal functions not working (see Microsoft
516 * Knowledge Base, article 104641) */
518 vlc_thread_t th = malloc (sizeof (*th));
525 #if defined( UNDER_CE )
526 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
528 hThread = (HANDLE)(uintptr_t)
529 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
534 /* Thread closes the handle when exiting, duplicate it here
535 * to be on the safe side when joining. */
536 if (!DuplicateHandle (GetCurrentProcess (), hThread,
537 GetCurrentProcess (), &th->handle, 0, FALSE,
538 DUPLICATE_SAME_ACCESS))
540 CloseHandle (hThread);
545 ResumeThread (hThread);
547 SetThreadPriority (hThread, priority);
558 #elif defined( HAVE_KERNEL_SCHEDULER_H )
559 *p_handle = spawn_thread( entry, psz_name, priority, data );
560 ret = resume_thread( *p_handle );
567 /* APC procedure for thread cancellation */
568 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
571 vlc_control_cancel (VLC_DO_CANCEL);
576 * Marks a thread as cancelled. Next time the target thread reaches a
577 * cancellation point (while not having disabled cancellation), it will
578 * run its cancellation cleanup handler, the thread variable destructors, and
579 * terminate. vlc_join() must be used afterward regardless of a thread being
582 void vlc_cancel (vlc_thread_t thread_id)
584 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
585 pthread_cancel (thread_id);
586 #elif defined (WIN32)
587 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
589 # warning vlc_cancel is not implemented!
594 * Waits for a thread to complete (if needed), and destroys it.
595 * This is a cancellation point; in case of cancellation, the join does _not_
598 * @param handle thread handle
599 * @param p_result [OUT] pointer to write the thread return value or NULL
600 * @return 0 on success, a standard error code otherwise.
602 void vlc_join (vlc_thread_t handle, void **result)
604 #if defined( LIBVLC_USE_PTHREAD )
605 int val = pthread_join (handle, result);
607 vlc_pthread_fatal ("joining thread", val, __FILE__, __LINE__);
609 #elif defined( UNDER_CE ) || defined( WIN32 )
612 while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
613 == WAIT_IO_COMPLETION);
615 CloseHandle (handle->handle);
617 *result = handle->data;
620 #elif defined( HAVE_KERNEL_SCHEDULER_H )
622 int val = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
624 *result = (void *)exit_value;
630 struct vlc_thread_boot
632 void * (*entry) (vlc_object_t *);
633 vlc_object_t *object;
636 static void *thread_entry (void *data)
638 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
639 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
642 msg_Dbg (obj, "thread started");
644 msg_Dbg (obj, "thread ended");
649 /*****************************************************************************
650 * vlc_thread_create: create a thread, inner version
651 *****************************************************************************
652 * Note that i_priority is only taken into account on platforms supporting
653 * userland real-time priority threads.
654 *****************************************************************************/
655 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
656 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
657 int i_priority, bool b_wait )
660 vlc_object_internals_t *p_priv = vlc_internals( p_this );
662 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
666 boot->object = p_this;
668 vlc_object_lock( p_this );
670 /* Make sure we don't re-create a thread if the object has already one */
671 assert( !p_priv->b_thread );
673 #if defined( LIBVLC_USE_PTHREAD )
675 if( config_GetInt( p_this, "rt-priority" ) > 0 )
678 /* Hack to avoid error msg */
679 if( config_GetType( p_this, "rt-offset" ) )
680 i_priority += config_GetInt( p_this, "rt-offset" );
684 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
689 msg_Dbg( p_this, "waiting for thread initialization" );
690 vlc_object_wait( p_this );
693 p_priv->b_thread = true;
694 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
695 (unsigned long)p_priv->thread_id, psz_name, i_priority,
701 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
702 psz_name, psz_file, i_line );
705 vlc_object_unlock( p_this );
709 /*****************************************************************************
710 * vlc_thread_set_priority: set the priority of the current thread when we
711 * couldn't set it in vlc_thread_create (for instance for the main thread)
712 *****************************************************************************/
713 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
714 int i_line, int i_priority )
716 vlc_object_internals_t *p_priv = vlc_internals( p_this );
718 if( !p_priv->b_thread )
720 msg_Err( p_this, "couldn't set priority of non-existent thread" );
724 #if defined( LIBVLC_USE_PTHREAD )
726 if( config_GetInt( p_this, "rt-priority" ) > 0 )
729 int i_error, i_policy;
730 struct sched_param param;
732 memset( ¶m, 0, sizeof(struct sched_param) );
733 if( config_GetType( p_this, "rt-offset" ) )
734 i_priority += config_GetInt( p_this, "rt-offset" );
735 if( i_priority <= 0 )
737 param.sched_priority = (-1) * i_priority;
738 i_policy = SCHED_OTHER;
742 param.sched_priority = i_priority;
745 if( (i_error = pthread_setschedparam( p_priv->thread_id,
746 i_policy, ¶m )) )
749 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
755 #elif defined( WIN32 ) || defined( UNDER_CE )
756 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
758 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
760 msg_Warn( p_this, "couldn't set a faster priority" );
769 /*****************************************************************************
770 * vlc_thread_join: wait until a thread exits, inner version
771 *****************************************************************************/
772 void __vlc_thread_join( vlc_object_t *p_this )
774 vlc_object_internals_t *p_priv = vlc_internals( p_this );
776 #if defined( LIBVLC_USE_PTHREAD )
777 vlc_join (p_priv->thread_id, NULL);
779 #elif defined( UNDER_CE ) || defined( WIN32 )
781 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
782 int64_t real_time, kernel_time, user_time;
784 if( ! DuplicateHandle(GetCurrentProcess(),
785 p_priv->thread_id->handle,
790 DUPLICATE_SAME_ACCESS) )
792 p_priv->b_thread = false;
793 return; /* We have a problem! */
796 vlc_join( p_priv->thread_id, NULL );
798 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
801 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
802 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
806 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
807 kernel_ft.dwLowDateTime) / 10;
810 ((((int64_t)user_ft.dwHighDateTime)<<32)|
811 user_ft.dwLowDateTime) / 10;
813 msg_Dbg( p_this, "thread times: "
814 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
815 real_time/60/1000000,
816 (double)((real_time%(60*1000000))/1000000.0),
817 kernel_time/60/1000000,
818 (double)((kernel_time%(60*1000000))/1000000.0),
819 user_time/60/1000000,
820 (double)((user_time%(60*1000000))/1000000.0) );
822 CloseHandle( hThread );
825 vlc_join( p_priv->thread_id, NULL );
829 p_priv->b_thread = false;
832 void vlc_thread_cancel (vlc_object_t *obj)
834 vlc_object_internals_t *priv = vlc_internals (obj);
837 vlc_cancel (priv->thread_id);
840 void vlc_control_cancel (int cmd, ...)
842 /* NOTE: This function only modifies thread-specific data, so there is no
843 * need to lock anything. */
844 #ifdef LIBVLC_USE_PTHREAD_CANCEL
852 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
856 /* Main thread - cannot be cancelled anyway */
859 nfo = malloc (sizeof (*nfo));
861 return; /* Uho! Expect problems! */
862 *nfo = VLC_CANCEL_INIT;
863 vlc_threadvar_set (&cancel_key, nfo);
869 case VLC_SAVE_CANCEL:
871 int *p_state = va_arg (ap, int *);
872 *p_state = nfo->killable;
873 nfo->killable = false;
877 case VLC_RESTORE_CANCEL:
879 int state = va_arg (ap, int);
880 nfo->killable = state != 0;
884 case VLC_TEST_CANCEL:
885 if (nfo->killable && nfo->killed)
887 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
890 #if defined (LIBVLC_USE_PTHREAD)
891 pthread_exit (PTHREAD_CANCELLED);
892 #elif defined (WIN32)
895 # error Not implemented!
904 case VLC_CLEANUP_PUSH:
906 /* cleaner is a pointer to the caller stack, no need to allocate
907 * and copy anything. As a nice side effect, this cannot fail. */
908 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
909 cleaner->next = nfo->cleaners;
910 nfo->cleaners = cleaner;
914 case VLC_CLEANUP_POP:
916 nfo->cleaners = nfo->cleaners->next;