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 );
71 * Object running the current thread
73 static vlc_threadvar_t thread_object_key;
75 vlc_object_t *vlc_threadobj (void)
77 return vlc_threadvar_get (&thread_object_key);
81 vlc_threadvar_t msg_context_global_key;
83 #if defined(LIBVLC_USE_PTHREAD)
84 static inline unsigned long vlc_threadid (void)
86 union { pthread_t th; unsigned long int i; } v = { };
87 v.th = pthread_self ();
91 #if defined(HAVE_EXECINFO_H) && defined(HAVE_BACKTRACE)
92 # include <execinfo.h>
95 /*****************************************************************************
96 * vlc_thread_fatal: Report an error from the threading layer
97 *****************************************************************************
98 * This is mostly meant for debugging.
99 *****************************************************************************/
100 void vlc_pthread_fatal (const char *action, int error,
101 const char *file, unsigned line)
103 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
104 action, vlc_threadid (), file, line, error);
106 /* Sometimes strerror_r() crashes too, so make sure we print an error
107 * message before we invoke it */
109 /* Avoid the strerror_r() prototype brain damage in glibc */
111 fprintf (stderr, " Error message: %m at:\n");
116 switch (strerror_r (error, buf, sizeof (buf)))
121 case ERANGE: /* should never happen */
122 msg = "unknwon (too big to display)";
125 msg = "unknown (invalid error number)";
128 fprintf (stderr, " Error message: %s\n", msg);
132 #ifdef HAVE_BACKTRACE
134 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
135 backtrace_symbols_fd (stack, len, 2);
141 void vlc_pthread_fatal (const char *action, int error,
142 const char *file, unsigned line)
144 (void)action; (void)error; (void)file; (void)line;
148 static vlc_threadvar_t cancel_key;
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. */
180 vlc_threadvar_create( &thread_object_key, NULL );
182 vlc_threadvar_create( &msg_context_global_key, msg_StackDestroy );
183 #ifndef LIBVLC_USE_PTHREAD
184 vlc_threadvar_create( &cancel_key, free );
190 /* If we have lazy mutex initialization support, unlock the mutex.
191 * Otherwize, we are screwed. */
192 #if defined( LIBVLC_USE_PTHREAD )
193 pthread_mutex_unlock( &once_mutex );
199 /*****************************************************************************
200 * vlc_threads_end: stop threads system
201 *****************************************************************************
202 * FIXME: This function is far from being threadsafe.
203 *****************************************************************************/
204 void vlc_threads_end( void )
206 #if defined( LIBVLC_USE_PTHREAD )
207 pthread_mutex_lock( &once_mutex );
210 assert( i_initializations > 0 );
212 if( i_initializations == 1 )
214 vlc_object_release( p_root );
215 #ifndef LIBVLC_USE_PTHREAD
216 vlc_threadvar_delete( &cancel_key );
218 vlc_threadvar_delete( &msg_context_global_key );
220 vlc_threadvar_delete( &thread_object_key );
225 #if defined( LIBVLC_USE_PTHREAD )
226 pthread_mutex_unlock( &once_mutex );
230 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
231 /* This is not prototyped under glibc, though it exists. */
232 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
235 /*****************************************************************************
236 * vlc_mutex_init: initialize a mutex
237 *****************************************************************************/
238 int vlc_mutex_init( vlc_mutex_t *p_mutex )
240 #if defined( LIBVLC_USE_PTHREAD )
241 pthread_mutexattr_t attr;
244 pthread_mutexattr_init( &attr );
247 /* Create error-checking mutex to detect problems more easily. */
248 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
249 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
251 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
254 i_result = pthread_mutex_init( p_mutex, &attr );
255 pthread_mutexattr_destroy( &attr );
257 #elif defined( UNDER_CE )
258 InitializeCriticalSection( &p_mutex->csection );
261 #elif defined( WIN32 )
262 *p_mutex = CreateMutex( 0, FALSE, 0 );
263 return (*p_mutex != NULL) ? 0 : ENOMEM;
265 #elif defined( HAVE_KERNEL_SCHEDULER_H )
266 /* check the arguments and whether it's already been initialized */
267 if( p_mutex == NULL )
272 if( p_mutex->init == 9999 )
277 p_mutex->lock = create_sem( 1, "BeMutex" );
278 if( p_mutex->lock < B_NO_ERROR )
283 p_mutex->init = 9999;
289 /*****************************************************************************
290 * vlc_mutex_init: initialize a recursive mutex (Do not use)
291 *****************************************************************************/
292 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
294 #if defined( LIBVLC_USE_PTHREAD )
295 pthread_mutexattr_t attr;
298 pthread_mutexattr_init( &attr );
299 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
300 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
302 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
304 i_result = pthread_mutex_init( p_mutex, &attr );
305 pthread_mutexattr_destroy( &attr );
307 #elif defined( WIN32 )
308 /* Create mutex returns a recursive mutex */
309 *p_mutex = CreateMutex( 0, FALSE, 0 );
310 return (*p_mutex != NULL) ? 0 : ENOMEM;
312 # error Unimplemented!
317 /*****************************************************************************
318 * vlc_mutex_destroy: destroy a mutex, inner version
319 *****************************************************************************/
320 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
322 #if defined( LIBVLC_USE_PTHREAD )
323 int val = pthread_mutex_destroy( p_mutex );
324 VLC_THREAD_ASSERT ("destroying mutex");
326 #elif defined( UNDER_CE )
327 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
329 DeleteCriticalSection( &p_mutex->csection );
331 #elif defined( WIN32 )
332 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
334 CloseHandle( *p_mutex );
336 #elif defined( HAVE_KERNEL_SCHEDULER_H )
337 if( p_mutex->init == 9999 )
338 delete_sem( p_mutex->lock );
345 /*****************************************************************************
346 * vlc_cond_init: initialize a condition
347 *****************************************************************************/
348 int __vlc_cond_init( vlc_cond_t *p_condvar )
350 #if defined( LIBVLC_USE_PTHREAD )
351 pthread_condattr_t attr;
354 ret = pthread_condattr_init (&attr);
358 # if !defined (_POSIX_CLOCK_SELECTION)
359 /* Fairly outdated POSIX support (that was defined in 2001) */
360 # define _POSIX_CLOCK_SELECTION (-1)
362 # if (_POSIX_CLOCK_SELECTION >= 0)
363 /* NOTE: This must be the same clock as the one in mtime.c */
364 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
367 ret = pthread_cond_init (p_condvar, &attr);
368 pthread_condattr_destroy (&attr);
371 #elif defined( UNDER_CE ) || defined( WIN32 )
372 /* Create an auto-reset event. */
373 *p_condvar = CreateEvent( NULL, /* no security */
374 FALSE, /* auto-reset event */
375 FALSE, /* start non-signaled */
376 NULL ); /* unnamed */
377 return *p_condvar ? 0 : ENOMEM;
379 #elif defined( HAVE_KERNEL_SCHEDULER_H )
385 if( p_condvar->init == 9999 )
390 p_condvar->thread = -1;
391 p_condvar->init = 9999;
397 /*****************************************************************************
398 * vlc_cond_destroy: destroy a condition, inner version
399 *****************************************************************************/
400 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
402 #if defined( LIBVLC_USE_PTHREAD )
403 int val = pthread_cond_destroy( p_condvar );
404 VLC_THREAD_ASSERT ("destroying condition");
406 #elif defined( UNDER_CE ) || defined( WIN32 )
407 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
409 CloseHandle( *p_condvar );
411 #elif defined( HAVE_KERNEL_SCHEDULER_H )
417 /*****************************************************************************
418 * vlc_tls_create: create a thread-local variable
419 *****************************************************************************/
420 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
424 #if defined( LIBVLC_USE_PTHREAD )
425 i_ret = pthread_key_create( p_tls, destr );
426 #elif defined( UNDER_CE )
428 #elif defined( WIN32 )
429 /* FIXME: remember/use the destr() callback and stop leaking whatever */
431 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
433 # error Unimplemented!
438 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
440 #if defined( LIBVLC_USE_PTHREAD )
441 pthread_key_delete (*p_tls);
442 #elif defined( UNDER_CE )
443 #elif defined( WIN32 )
446 # error Unimplemented!
450 #if defined (LIBVLC_USE_PTHREAD)
451 #elif defined (WIN32)
452 static unsigned __stdcall vlc_entry (void *data)
454 vlc_thread_t self = data;
455 self->data = self->entry (self->data);
461 * Creates and starts new thread.
463 * @param p_handle [OUT] pointer to write the handle of the created thread to
464 * @param entry entry point for the thread
465 * @param data data parameter given to the entry point
466 * @param priority thread priority value
467 * @return 0 on success, a standard error code on error.
469 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
474 #if defined( LIBVLC_USE_PTHREAD )
476 pthread_attr_init (&attr);
478 /* Block the signals that signals interface plugin handles.
479 * If the LibVLC caller wants to handle some signals by itself, it should
480 * block these before whenever invoking LibVLC. And it must obviously not
481 * start the VLC signals interface plugin.
483 * LibVLC will normally ignore any interruption caused by an asynchronous
484 * signal during a system call. But there may well be some buggy cases
485 * where it fails to handle EINTR (bug reports welcome). Some underlying
486 * libraries might also not handle EINTR properly.
492 sigdelset (&set, SIGHUP);
493 sigaddset (&set, SIGINT);
494 sigaddset (&set, SIGQUIT);
495 sigaddset (&set, SIGTERM);
497 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
498 pthread_sigmask (SIG_BLOCK, &set, &oldset);
501 struct sched_param sp = { .sched_priority = priority, };
504 if (sp.sched_priority <= 0)
505 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
507 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
509 pthread_attr_setschedpolicy (&attr, policy);
510 pthread_attr_setschedparam (&attr, &sp);
513 ret = pthread_create (p_handle, &attr, entry, data);
514 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
515 pthread_attr_destroy (&attr);
517 #elif defined( WIN32 ) || defined( UNDER_CE )
518 /* When using the MSVCRT C library you have to use the _beginthreadex
519 * function instead of CreateThread, otherwise you'll end up with
520 * memory leaks and the signal functions not working (see Microsoft
521 * Knowledge Base, article 104641) */
523 vlc_thread_t th = malloc (sizeof (*p_handle));
530 #if defined( UNDER_CE )
531 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
533 hThread = (HANDLE)(uintptr_t)
534 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
539 /* Thread closes the handle when exiting, duplicate it here
540 * to be on the safe side when joining. */
541 if (!DuplicateHandle (GetCurrentProcess (), hThread,
542 GetCurrentProcess (), &th->handle, 0, FALSE,
543 DUPLICATE_SAME_ACCESS))
545 CloseHandle (hThread);
550 ResumeThread (hThread);
552 SetThreadPriority (hThread, priority);
563 #elif defined( HAVE_KERNEL_SCHEDULER_H )
564 *p_handle = spawn_thread( entry, psz_name, priority, data );
565 ret = resume_thread( *p_handle );
572 /* APC procedure for thread cancellation */
573 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
576 vlc_control_cancel (VLC_DO_CANCEL);
581 * Marks a thread as cancelled. Next time the target thread reaches a
582 * cancellation point (while not having disabled cancellation), it will
583 * run its cancellation cleanup handler, the thread variable destructors, and
584 * terminate. vlc_join() must be used afterward regardless of a thread being
587 void vlc_cancel (vlc_thread_t thread_id)
589 #if defined (LIBVLC_USE_PTHREAD)
590 pthread_cancel (thread_id);
591 #elif defined (WIN32)
592 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
597 * Waits for a thread to complete (if needed), and destroys it.
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 int vlc_join (vlc_thread_t handle, void **result)
604 #if defined( LIBVLC_USE_PTHREAD )
605 return pthread_join (handle, result);
607 #elif defined( UNDER_CE ) || defined( WIN32 )
608 WaitForSingleObject (handle->handle, INFINITE);
609 CloseHandle (handle->handle);
611 *result = handle->data;
615 #elif defined( HAVE_KERNEL_SCHEDULER_H )
617 ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
619 *result = (void *)exit_value;
626 struct vlc_thread_boot
628 void * (*entry) (vlc_object_t *);
629 vlc_object_t *object;
632 static void *thread_entry (void *data)
634 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
635 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
639 vlc_threadvar_set (&thread_object_key, obj);
641 msg_Dbg (obj, "thread started");
643 msg_Dbg (obj, "thread ended");
648 /*****************************************************************************
649 * vlc_thread_create: create a thread, inner version
650 *****************************************************************************
651 * Note that i_priority is only taken into account on platforms supporting
652 * userland real-time priority threads.
653 *****************************************************************************/
654 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
655 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
656 int i_priority, bool b_wait )
659 vlc_object_internals_t *p_priv = vlc_internals( p_this );
661 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
665 boot->object = p_this;
667 vlc_object_lock( p_this );
669 /* Make sure we don't re-create a thread if the object has already one */
670 assert( !p_priv->b_thread );
672 #if defined( LIBVLC_USE_PTHREAD )
674 if( config_GetInt( p_this, "rt-priority" ) > 0 )
677 /* Hack to avoid error msg */
678 if( config_GetType( p_this, "rt-offset" ) )
679 i_priority += config_GetInt( p_this, "rt-offset" );
683 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
688 msg_Dbg( p_this, "waiting for thread initialization" );
689 vlc_object_wait( p_this );
692 p_priv->b_thread = true;
693 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
694 (unsigned long)p_priv->thread_id, psz_name, i_priority,
700 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
701 psz_name, psz_file, i_line );
704 vlc_object_unlock( p_this );
708 /*****************************************************************************
709 * vlc_thread_set_priority: set the priority of the current thread when we
710 * couldn't set it in vlc_thread_create (for instance for the main thread)
711 *****************************************************************************/
712 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
713 int i_line, int i_priority )
715 vlc_object_internals_t *p_priv = vlc_internals( p_this );
717 if( !p_priv->b_thread )
719 msg_Err( p_this, "couldn't set priority of non-existent thread" );
723 #if defined( LIBVLC_USE_PTHREAD )
725 if( config_GetInt( p_this, "rt-priority" ) > 0 )
728 int i_error, i_policy;
729 struct sched_param param;
731 memset( ¶m, 0, sizeof(struct sched_param) );
732 if( config_GetType( p_this, "rt-offset" ) )
733 i_priority += config_GetInt( p_this, "rt-offset" );
734 if( i_priority <= 0 )
736 param.sched_priority = (-1) * i_priority;
737 i_policy = SCHED_OTHER;
741 param.sched_priority = i_priority;
744 if( (i_error = pthread_setschedparam( p_priv->thread_id,
745 i_policy, ¶m )) )
748 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
754 #elif defined( WIN32 ) || defined( UNDER_CE )
755 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
757 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
759 msg_Warn( p_this, "couldn't set a faster priority" );
768 /*****************************************************************************
769 * vlc_thread_join: wait until a thread exits, inner version
770 *****************************************************************************/
771 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
773 vlc_object_internals_t *p_priv = vlc_internals( p_this );
776 #if defined( LIBVLC_USE_PTHREAD )
777 /* Make sure we do return if we are calling vlc_thread_join()
778 * from the joined thread */
779 if (pthread_equal (pthread_self (), p_priv->thread_id))
781 msg_Warn (p_this, "joining the active thread (VLC might crash)");
782 i_ret = pthread_detach (p_priv->thread_id);
785 i_ret = vlc_join (p_priv->thread_id, NULL);
787 #elif defined( UNDER_CE ) || defined( WIN32 )
789 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
790 int64_t real_time, kernel_time, user_time;
792 if( ! DuplicateHandle(GetCurrentProcess(),
793 p_priv->thread_id->handle,
798 DUPLICATE_SAME_ACCESS) )
800 p_priv->b_thread = false;
801 i_ret = GetLastError();
805 vlc_join( p_priv->thread_id, NULL );
807 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
810 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
811 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
815 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
816 kernel_ft.dwLowDateTime) / 10;
819 ((((int64_t)user_ft.dwHighDateTime)<<32)|
820 user_ft.dwLowDateTime) / 10;
822 msg_Dbg( p_this, "thread times: "
823 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
824 real_time/60/1000000,
825 (double)((real_time%(60*1000000))/1000000.0),
826 kernel_time/60/1000000,
827 (double)((kernel_time%(60*1000000))/1000000.0),
828 user_time/60/1000000,
829 (double)((user_time%(60*1000000))/1000000.0) );
831 CloseHandle( hThread );
835 i_ret = vlc_join( p_priv->thread_id, NULL );
842 msg_Err( p_this, "thread_join(%lu) failed at %s:%d (%m)",
843 (unsigned long)p_priv->thread_id, psz_file, i_line );
846 msg_Dbg( p_this, "thread %lu joined (%s:%d)",
847 (unsigned long)p_priv->thread_id, psz_file, i_line );
849 p_priv->b_thread = false;
852 void vlc_thread_cancel (vlc_object_t *obj)
854 vlc_object_internals_t *priv = vlc_internals (obj);
857 vlc_cancel (priv->thread_id);
860 typedef struct vlc_cleanup_t
862 struct vlc_cleanup_t *next;
863 void (*proc) (void *);
867 typedef struct vlc_cancel_t
869 vlc_cleanup_t *cleaners;
874 void vlc_control_cancel (int cmd, ...)
876 #ifdef LIBVLC_USE_PTHREAD
884 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
887 nfo = malloc (sizeof (*nfo));
890 nfo->cleaners = NULL;
892 nfo->killable = true;
897 case VLC_SAVE_CANCEL:
899 int *p_state = va_arg (ap, int *);
900 *p_state = nfo->killable;
901 nfo->killable = false;
905 case VLC_RESTORE_CANCEL:
907 int state = va_arg (ap, int);
908 nfo->killable = state != 0;
912 case VLC_TEST_CANCEL:
913 if (nfo->killable && nfo->killed)
915 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
918 #if defined (LIBVLC_USE_PTHREAD)
919 pthread_exit (PTHREAD_CANCELLED);
920 #elif defined (WIN32)
923 # error Not implemented!