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;
149 /*****************************************************************************
150 * vlc_threads_init: initialize threads system
151 *****************************************************************************
152 * This function requires lazy initialization of a global lock in order to
153 * keep the library really thread-safe. Some architectures don't support this
154 * and thus do not guarantee the complete reentrancy.
155 *****************************************************************************/
156 int vlc_threads_init( void )
158 int i_ret = VLC_SUCCESS;
160 /* If we have lazy mutex initialization, use it. Otherwise, we just
161 * hope nothing wrong happens. */
162 #if defined( LIBVLC_USE_PTHREAD )
163 pthread_mutex_lock( &once_mutex );
166 if( i_initializations == 0 )
168 p_root = vlc_custom_create( (vlc_object_t *)NULL, sizeof( *p_root ),
169 VLC_OBJECT_GENERIC, "root" );
176 /* We should be safe now. Do all the initialization stuff we want. */
178 vlc_threadvar_create( &thread_object_key, NULL );
180 vlc_threadvar_create( &msg_context_global_key, msg_StackDestroy );
185 /* If we have lazy mutex initialization support, unlock the mutex.
186 * Otherwize, we are screwed. */
187 #if defined( LIBVLC_USE_PTHREAD )
188 pthread_mutex_unlock( &once_mutex );
194 /*****************************************************************************
195 * vlc_threads_end: stop threads system
196 *****************************************************************************
197 * FIXME: This function is far from being threadsafe.
198 *****************************************************************************/
199 void vlc_threads_end( void )
201 #if defined( LIBVLC_USE_PTHREAD )
202 pthread_mutex_lock( &once_mutex );
205 assert( i_initializations > 0 );
207 if( i_initializations == 1 )
209 vlc_object_release( p_root );
210 vlc_threadvar_delete( &msg_context_global_key );
212 vlc_threadvar_delete( &thread_object_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_thread_t self = data;
447 self->data = self->entry (self->data);
453 * Creates and starts new thread.
455 * @param p_handle [OUT] pointer to write the handle of the created thread to
456 * @param entry entry point for the thread
457 * @param data data parameter given to the entry point
458 * @param priority thread priority value
459 * @return 0 on success, a standard error code on error.
461 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
466 #if defined( LIBVLC_USE_PTHREAD )
468 pthread_attr_init (&attr);
470 /* Block the signals that signals interface plugin handles.
471 * If the LibVLC caller wants to handle some signals by itself, it should
472 * block these before whenever invoking LibVLC. And it must obviously not
473 * start the VLC signals interface plugin.
475 * LibVLC will normally ignore any interruption caused by an asynchronous
476 * signal during a system call. But there may well be some buggy cases
477 * where it fails to handle EINTR (bug reports welcome). Some underlying
478 * libraries might also not handle EINTR properly.
484 sigdelset (&set, SIGHUP);
485 sigaddset (&set, SIGINT);
486 sigaddset (&set, SIGQUIT);
487 sigaddset (&set, SIGTERM);
489 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
490 pthread_sigmask (SIG_BLOCK, &set, &oldset);
493 struct sched_param sp = { .sched_priority = priority, };
496 if (sp.sched_priority <= 0)
497 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
499 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
501 pthread_attr_setschedpolicy (&attr, policy);
502 pthread_attr_setschedparam (&attr, &sp);
505 ret = pthread_create (p_handle, &attr, entry, data);
506 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
507 pthread_attr_destroy (&attr);
509 #elif defined( WIN32 ) || defined( UNDER_CE )
510 /* When using the MSVCRT C library you have to use the _beginthreadex
511 * function instead of CreateThread, otherwise you'll end up with
512 * memory leaks and the signal functions not working (see Microsoft
513 * Knowledge Base, article 104641) */
515 vlc_thread_t th = malloc (sizeof (*p_handle));
522 #if defined( UNDER_CE )
523 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
525 hThread = (HANDLE)(uintptr_t)
526 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
531 /* Thread closes the handle when exiting, duplicate it here
532 * to be on the safe side when joining. */
533 if (!DuplicateHandle (GetCurrentProcess (), hThread,
534 GetCurrentProcess (), &th->handle, 0, FALSE,
535 DUPLICATE_SAME_ACCESS))
537 CloseHandle (hThread);
542 ResumeThread (hThread);
544 SetThreadPriority (hThread, priority);
555 #elif defined( HAVE_KERNEL_SCHEDULER_H )
556 *p_handle = spawn_thread( entry, psz_name, priority, data );
557 ret = resume_thread( *p_handle );
564 * Marks a thread as cancelled. Next time the target thread reaches a
565 * cancellation point (while not having disabled cancellation), it will
566 * run its cancellation cleanup handler, the thread variable destructors, and
567 * terminate. vlc_join() must be used afterward regardless of a thread being
570 void vlc_cancel (vlc_thread_t thread_id)
572 #if defined (LIBVLC_USE_PTHREAD)
573 pthread_cancel (thread_id);
578 * Waits for a thread to complete (if needed), and destroys it.
579 * @param handle thread handle
580 * @param p_result [OUT] pointer to write the thread return value or NULL
581 * @return 0 on success, a standard error code otherwise.
583 int vlc_join (vlc_thread_t handle, void **result)
585 #if defined( LIBVLC_USE_PTHREAD )
586 return pthread_join (handle, result);
588 #elif defined( UNDER_CE ) || defined( WIN32 )
589 WaitForSingleObject (handle->handle, INFINITE);
590 CloseHandle (handle->handle);
592 *result = handle->data;
596 #elif defined( HAVE_KERNEL_SCHEDULER_H )
598 ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
600 *result = (void *)exit_value;
607 struct vlc_thread_boot
609 void * (*entry) (vlc_object_t *);
610 vlc_object_t *object;
613 static void *thread_entry (void *data)
615 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
616 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
620 vlc_threadvar_set (&thread_object_key, obj);
622 msg_Dbg (obj, "thread started");
624 msg_Dbg (obj, "thread ended");
629 /*****************************************************************************
630 * vlc_thread_create: create a thread, inner version
631 *****************************************************************************
632 * Note that i_priority is only taken into account on platforms supporting
633 * userland real-time priority threads.
634 *****************************************************************************/
635 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
636 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
637 int i_priority, bool b_wait )
640 vlc_object_internals_t *p_priv = vlc_internals( p_this );
642 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
646 boot->object = p_this;
648 vlc_object_lock( p_this );
650 /* Make sure we don't re-create a thread if the object has already one */
651 assert( !p_priv->b_thread );
653 #if defined( LIBVLC_USE_PTHREAD )
655 if( config_GetInt( p_this, "rt-priority" ) > 0 )
658 /* Hack to avoid error msg */
659 if( config_GetType( p_this, "rt-offset" ) )
660 i_priority += config_GetInt( p_this, "rt-offset" );
664 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
669 msg_Dbg( p_this, "waiting for thread initialization" );
670 vlc_object_wait( p_this );
673 p_priv->b_thread = true;
674 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
675 (unsigned long)p_priv->thread_id, psz_name, i_priority,
681 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
682 psz_name, psz_file, i_line );
685 vlc_object_unlock( p_this );
689 /*****************************************************************************
690 * vlc_thread_set_priority: set the priority of the current thread when we
691 * couldn't set it in vlc_thread_create (for instance for the main thread)
692 *****************************************************************************/
693 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
694 int i_line, int i_priority )
696 vlc_object_internals_t *p_priv = vlc_internals( p_this );
698 if( !p_priv->b_thread )
700 msg_Err( p_this, "couldn't set priority of non-existent thread" );
704 #if defined( LIBVLC_USE_PTHREAD )
706 if( config_GetInt( p_this, "rt-priority" ) > 0 )
709 int i_error, i_policy;
710 struct sched_param param;
712 memset( ¶m, 0, sizeof(struct sched_param) );
713 if( config_GetType( p_this, "rt-offset" ) )
714 i_priority += config_GetInt( p_this, "rt-offset" );
715 if( i_priority <= 0 )
717 param.sched_priority = (-1) * i_priority;
718 i_policy = SCHED_OTHER;
722 param.sched_priority = i_priority;
725 if( (i_error = pthread_setschedparam( p_priv->thread_id,
726 i_policy, ¶m )) )
729 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
735 #elif defined( WIN32 ) || defined( UNDER_CE )
736 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
738 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
740 msg_Warn( p_this, "couldn't set a faster priority" );
749 /*****************************************************************************
750 * vlc_thread_join: wait until a thread exits, inner version
751 *****************************************************************************/
752 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
754 vlc_object_internals_t *p_priv = vlc_internals( p_this );
757 #if defined( LIBVLC_USE_PTHREAD )
758 /* Make sure we do return if we are calling vlc_thread_join()
759 * from the joined thread */
760 if (pthread_equal (pthread_self (), p_priv->thread_id))
762 msg_Warn (p_this, "joining the active thread (VLC might crash)");
763 i_ret = pthread_detach (p_priv->thread_id);
766 i_ret = vlc_join (p_priv->thread_id, NULL);
768 #elif defined( UNDER_CE ) || defined( WIN32 )
770 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
771 int64_t real_time, kernel_time, user_time;
773 if( ! DuplicateHandle(GetCurrentProcess(),
774 p_priv->thread_id->handle,
779 DUPLICATE_SAME_ACCESS) )
781 p_priv->b_thread = false;
782 i_ret = GetLastError();
786 vlc_join( p_priv->thread_id, NULL );
788 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
791 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
792 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
796 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
797 kernel_ft.dwLowDateTime) / 10;
800 ((((int64_t)user_ft.dwHighDateTime)<<32)|
801 user_ft.dwLowDateTime) / 10;
803 msg_Dbg( p_this, "thread times: "
804 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
805 real_time/60/1000000,
806 (double)((real_time%(60*1000000))/1000000.0),
807 kernel_time/60/1000000,
808 (double)((kernel_time%(60*1000000))/1000000.0),
809 user_time/60/1000000,
810 (double)((user_time%(60*1000000))/1000000.0) );
812 CloseHandle( hThread );
816 i_ret = vlc_join( p_priv->thread_id, NULL );
823 msg_Err( p_this, "thread_join(%lu) failed at %s:%d (%m)",
824 (unsigned long)p_priv->thread_id, psz_file, i_line );
827 msg_Dbg( p_this, "thread %lu joined (%s:%d)",
828 (unsigned long)p_priv->thread_id, psz_file, i_line );
830 p_priv->b_thread = false;
833 void vlc_thread_cancel (vlc_object_t *obj)
835 vlc_object_internals_t *priv = vlc_internals (obj);
838 vlc_cancel (priv->thread_id);
841 void vlc_control_cancel (int cmd, ...)
843 #ifdef LIBVLC_USE_PTHREAD
847 static __thread struct vlc_cancel_t *stack = NULL;
848 static __thread bool killed = false, killable = true;
855 case VLC_SAVE_CANCEL:
857 int *p_state = va_arg (ap, int *);
863 case VLC_RESTORE_CANCEL:
865 int state = va_arg (ap, int);
866 killable = state != 0;
870 case VLC_TEST_CANCEL:
875 # error Not implemented!