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>
40 #define VLC_THREADS_UNINITIALIZED 0
41 #define VLC_THREADS_PENDING 1
42 #define VLC_THREADS_ERROR 2
43 #define VLC_THREADS_READY 3
45 /*****************************************************************************
46 * Global mutex for lazy initialization of the threads system
47 *****************************************************************************/
48 static volatile unsigned i_initializations = 0;
50 #if defined( LIBVLC_USE_PTHREAD )
53 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
57 * Global process-wide VLC object.
58 * Contains inter-instance data, such as the module cache and global mutexes.
60 static libvlc_global_data_t *p_root;
62 libvlc_global_data_t *vlc_global( void )
64 assert( i_initializations > 0 );
70 * Object running the current thread
72 static vlc_threadvar_t thread_object_key;
74 vlc_object_t *vlc_threadobj (void)
76 return vlc_threadvar_get (&thread_object_key);
80 vlc_threadvar_t msg_context_global_key;
82 #if defined(LIBVLC_USE_PTHREAD)
83 static inline unsigned long vlc_threadid (void)
85 union { pthread_t th; unsigned long int i; } v = { };
86 v.th = pthread_self ();
90 #if defined(HAVE_EXECINFO_H) && defined(HAVE_BACKTRACE)
91 # include <execinfo.h>
94 /*****************************************************************************
95 * vlc_thread_fatal: Report an error from the threading layer
96 *****************************************************************************
97 * This is mostly meant for debugging.
98 *****************************************************************************/
99 void vlc_pthread_fatal (const char *action, int error,
100 const char *file, unsigned line)
102 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
103 action, vlc_threadid (), file, line, error);
105 /* Sometimes strerror_r() crashes too, so make sure we print an error
106 * message before we invoke it */
108 /* Avoid the strerror_r() prototype brain damage in glibc */
110 fprintf (stderr, " Error message: %m at:\n");
115 switch (strerror_r (error, buf, sizeof (buf)))
120 case ERANGE: /* should never happen */
121 msg = "unknwon (too big to display)";
124 msg = "unknown (invalid error number)";
127 fprintf (stderr, " Error message: %s\n", msg);
131 #ifdef HAVE_BACKTRACE
133 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
134 backtrace_symbols_fd (stack, len, 2);
140 void vlc_pthread_fatal (const char *action, int error,
141 const char *file, unsigned line)
143 (void)action; (void)error; (void)file; (void)line;
148 /*****************************************************************************
149 * vlc_threads_init: initialize threads system
150 *****************************************************************************
151 * This function requires lazy initialization of a global lock in order to
152 * keep the library really thread-safe. Some architectures don't support this
153 * and thus do not guarantee the complete reentrancy.
154 *****************************************************************************/
155 int vlc_threads_init( void )
157 int i_ret = VLC_SUCCESS;
159 /* If we have lazy mutex initialization, use it. Otherwise, we just
160 * hope nothing wrong happens. */
161 #if defined( LIBVLC_USE_PTHREAD )
162 pthread_mutex_lock( &once_mutex );
165 if( i_initializations == 0 )
167 p_root = vlc_custom_create( (vlc_object_t *)NULL, sizeof( *p_root ),
168 VLC_OBJECT_GENERIC, "root" );
175 /* We should be safe now. Do all the initialization stuff we want. */
177 vlc_threadvar_create( &thread_object_key, NULL );
179 vlc_threadvar_create( &msg_context_global_key, msg_StackDestroy );
184 /* If we have lazy mutex initialization support, unlock the mutex.
185 * Otherwize, we are screwed. */
186 #if defined( LIBVLC_USE_PTHREAD )
187 pthread_mutex_unlock( &once_mutex );
193 /*****************************************************************************
194 * vlc_threads_end: stop threads system
195 *****************************************************************************
196 * FIXME: This function is far from being threadsafe.
197 *****************************************************************************/
198 void vlc_threads_end( void )
200 #if defined( LIBVLC_USE_PTHREAD )
201 pthread_mutex_lock( &once_mutex );
204 assert( i_initializations > 0 );
206 if( i_initializations == 1 )
208 vlc_object_release( p_root );
209 vlc_threadvar_delete( &msg_context_global_key );
211 vlc_threadvar_delete( &thread_object_key );
216 #if defined( LIBVLC_USE_PTHREAD )
217 pthread_mutex_unlock( &once_mutex );
221 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
222 /* This is not prototyped under glibc, though it exists. */
223 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
226 /*****************************************************************************
227 * vlc_mutex_init: initialize a mutex
228 *****************************************************************************/
229 int vlc_mutex_init( vlc_mutex_t *p_mutex )
231 #if defined( LIBVLC_USE_PTHREAD )
232 pthread_mutexattr_t attr;
235 pthread_mutexattr_init( &attr );
238 /* Create error-checking mutex to detect problems more easily. */
239 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
240 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
242 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
245 i_result = pthread_mutex_init( p_mutex, &attr );
246 pthread_mutexattr_destroy( &attr );
248 #elif defined( UNDER_CE )
249 InitializeCriticalSection( &p_mutex->csection );
252 #elif defined( WIN32 )
253 *p_mutex = CreateMutex( 0, FALSE, 0 );
254 return (*p_mutex != NULL) ? 0 : ENOMEM;
256 #elif defined( HAVE_KERNEL_SCHEDULER_H )
257 /* check the arguments and whether it's already been initialized */
258 if( p_mutex == NULL )
263 if( p_mutex->init == 9999 )
268 p_mutex->lock = create_sem( 1, "BeMutex" );
269 if( p_mutex->lock < B_NO_ERROR )
274 p_mutex->init = 9999;
280 /*****************************************************************************
281 * vlc_mutex_init: initialize a recursive mutex (Do not use)
282 *****************************************************************************/
283 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
285 #if defined( LIBVLC_USE_PTHREAD )
286 pthread_mutexattr_t attr;
289 pthread_mutexattr_init( &attr );
290 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
291 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
293 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
295 i_result = pthread_mutex_init( p_mutex, &attr );
296 pthread_mutexattr_destroy( &attr );
298 #elif defined( WIN32 )
299 /* Create mutex returns a recursive mutex */
300 *p_mutex = CreateMutex( 0, FALSE, 0 );
301 return (*p_mutex != NULL) ? 0 : ENOMEM;
303 # error Unimplemented!
308 /*****************************************************************************
309 * vlc_mutex_destroy: destroy a mutex, inner version
310 *****************************************************************************/
311 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
313 #if defined( LIBVLC_USE_PTHREAD )
314 int val = pthread_mutex_destroy( p_mutex );
315 VLC_THREAD_ASSERT ("destroying mutex");
317 #elif defined( UNDER_CE )
318 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
320 DeleteCriticalSection( &p_mutex->csection );
322 #elif defined( WIN32 )
323 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
325 CloseHandle( *p_mutex );
327 #elif defined( HAVE_KERNEL_SCHEDULER_H )
328 if( p_mutex->init == 9999 )
329 delete_sem( p_mutex->lock );
336 /*****************************************************************************
337 * vlc_cond_init: initialize a condition
338 *****************************************************************************/
339 int __vlc_cond_init( vlc_cond_t *p_condvar )
341 #if defined( LIBVLC_USE_PTHREAD )
342 pthread_condattr_t attr;
345 ret = pthread_condattr_init (&attr);
349 # if !defined (_POSIX_CLOCK_SELECTION)
350 /* Fairly outdated POSIX support (that was defined in 2001) */
351 # define _POSIX_CLOCK_SELECTION (-1)
353 # if (_POSIX_CLOCK_SELECTION >= 0)
354 /* NOTE: This must be the same clock as the one in mtime.c */
355 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
358 ret = pthread_cond_init (p_condvar, &attr);
359 pthread_condattr_destroy (&attr);
362 #elif defined( UNDER_CE ) || defined( WIN32 )
363 /* Create an auto-reset event. */
364 *p_condvar = CreateEvent( NULL, /* no security */
365 FALSE, /* auto-reset event */
366 FALSE, /* start non-signaled */
367 NULL ); /* unnamed */
368 return *p_condvar ? 0 : ENOMEM;
370 #elif defined( HAVE_KERNEL_SCHEDULER_H )
376 if( p_condvar->init == 9999 )
381 p_condvar->thread = -1;
382 p_condvar->init = 9999;
388 /*****************************************************************************
389 * vlc_cond_destroy: destroy a condition, inner version
390 *****************************************************************************/
391 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
393 #if defined( LIBVLC_USE_PTHREAD )
394 int val = pthread_cond_destroy( p_condvar );
395 VLC_THREAD_ASSERT ("destroying condition");
397 #elif defined( UNDER_CE ) || defined( WIN32 )
398 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
400 CloseHandle( *p_condvar );
402 #elif defined( HAVE_KERNEL_SCHEDULER_H )
408 /*****************************************************************************
409 * vlc_tls_create: create a thread-local variable
410 *****************************************************************************/
411 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
415 #if defined( LIBVLC_USE_PTHREAD )
416 i_ret = pthread_key_create( p_tls, destr );
417 #elif defined( UNDER_CE )
419 #elif defined( WIN32 )
420 /* FIXME: remember/use the destr() callback and stop leaking whatever */
422 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
424 # error Unimplemented!
429 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
431 #if defined( LIBVLC_USE_PTHREAD )
432 pthread_key_delete (*p_tls);
433 #elif defined( UNDER_CE )
434 #elif defined( WIN32 )
437 # error Unimplemented!
441 #if defined (LIBVLC_USE_PTHREAD)
442 #elif defined (WIN32)
443 static unsigned __stdcall vlc_entry (void *data)
445 vlc_thread_t self = data;
446 self->data = self->entry (self->data);
452 * Creates and starts new thread.
454 * @param p_handle [OUT] pointer to write the handle of the created thread to
455 * @param entry entry point for the thread
456 * @param data data parameter given to the entry point
457 * @param priority thread priority value
458 * @return 0 on success, a standard error code on error.
460 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
465 #if defined( LIBVLC_USE_PTHREAD )
467 pthread_attr_init (&attr);
469 /* Block the signals that signals interface plugin handles.
470 * If the LibVLC caller wants to handle some signals by itself, it should
471 * block these before whenever invoking LibVLC. And it must obviously not
472 * start the VLC signals interface plugin.
474 * LibVLC will normally ignore any interruption caused by an asynchronous
475 * signal during a system call. But there may well be some buggy cases
476 * where it fails to handle EINTR (bug reports welcome). Some underlying
477 * libraries might also not handle EINTR properly.
483 sigdelset (&set, SIGHUP);
484 sigaddset (&set, SIGINT);
485 sigaddset (&set, SIGQUIT);
486 sigaddset (&set, SIGTERM);
488 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
489 pthread_sigmask (SIG_BLOCK, &set, &oldset);
492 struct sched_param sp = { .sched_priority = priority, };
495 if (sp.sched_priority <= 0)
496 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
498 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
500 pthread_attr_setschedpolicy (&attr, policy);
501 pthread_attr_setschedparam (&attr, &sp);
504 ret = pthread_create (p_handle, &attr, entry, data);
505 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
506 pthread_attr_destroy (&attr);
508 #elif defined( WIN32 ) || defined( UNDER_CE )
509 /* When using the MSVCRT C library you have to use the _beginthreadex
510 * function instead of CreateThread, otherwise you'll end up with
511 * memory leaks and the signal functions not working (see Microsoft
512 * Knowledge Base, article 104641) */
514 vlc_thread_t th = malloc (sizeof (*p_handle));
521 #if defined( UNDER_CE )
522 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
524 hThread = (HANDLE)(uintptr_t)
525 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
530 /* Thread closes the handle when exiting, duplicate it here
531 * to be on the safe side when joining. */
532 if (!DuplicateHandle (GetCurrentProcess (), hThread,
533 GetCurrentProcess (), &th->handle, 0, FALSE,
534 DUPLICATE_SAME_ACCESS))
536 CloseHandle (hThread);
541 ResumeThread (hThread);
543 SetThreadPriority (hThread, priority);
554 #elif defined( HAVE_KERNEL_SCHEDULER_H )
555 *p_handle = spawn_thread( entry, psz_name, priority, data );
556 ret = resume_thread( *p_handle );
563 * Marks a thread as cancelled. Next time the target thread reaches a
564 * cancellation point (while not having disabled cancellation), it will
565 * run its cancellation cleanup handler, the thread variable destructors, and
566 * terminate. vlc_join() must be used afterward regardless of a thread being
569 void vlc_cancel (vlc_thread_t thread_id)
571 #if defined (LIBVLC_USE_PTHREAD)
572 pthread_cancel (thread_id);
577 * Waits for a thread to complete (if needed), and destroys it.
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 int vlc_join (vlc_thread_t handle, void **result)
584 #if defined( LIBVLC_USE_PTHREAD )
585 return pthread_join (handle, result);
587 #elif defined( UNDER_CE ) || defined( WIN32 )
588 WaitForSingleObject (handle->handle, INFINITE);
589 CloseHandle (handle->handle);
591 *result = handle->data;
595 #elif defined( HAVE_KERNEL_SCHEDULER_H )
597 ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
599 *result = (void *)exit_value;
606 struct vlc_thread_boot
608 void * (*entry) (vlc_object_t *);
609 vlc_object_t *object;
612 static void *thread_entry (void *data)
614 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
615 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
619 vlc_threadvar_set (&thread_object_key, obj);
621 msg_Dbg (obj, "thread started");
623 msg_Dbg (obj, "thread ended");
628 /*****************************************************************************
629 * vlc_thread_create: create a thread, inner version
630 *****************************************************************************
631 * Note that i_priority is only taken into account on platforms supporting
632 * userland real-time priority threads.
633 *****************************************************************************/
634 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
635 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
636 int i_priority, bool b_wait )
639 vlc_object_internals_t *p_priv = vlc_internals( p_this );
641 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
645 boot->object = p_this;
647 vlc_object_lock( p_this );
649 /* Make sure we don't re-create a thread if the object has already one */
650 assert( !p_priv->b_thread );
652 #if defined( LIBVLC_USE_PTHREAD )
654 if( config_GetInt( p_this, "rt-priority" ) > 0 )
657 /* Hack to avoid error msg */
658 if( config_GetType( p_this, "rt-offset" ) )
659 i_priority += config_GetInt( p_this, "rt-offset" );
663 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
668 msg_Dbg( p_this, "waiting for thread initialization" );
669 vlc_object_wait( p_this );
672 p_priv->b_thread = true;
673 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
674 (unsigned long)p_priv->thread_id, psz_name, i_priority,
680 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
681 psz_name, psz_file, i_line );
684 vlc_object_unlock( p_this );
688 /*****************************************************************************
689 * vlc_thread_set_priority: set the priority of the current thread when we
690 * couldn't set it in vlc_thread_create (for instance for the main thread)
691 *****************************************************************************/
692 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
693 int i_line, int i_priority )
695 vlc_object_internals_t *p_priv = vlc_internals( p_this );
697 if( !p_priv->b_thread )
699 msg_Err( p_this, "couldn't set priority of non-existent thread" );
703 #if defined( LIBVLC_USE_PTHREAD )
705 if( config_GetInt( p_this, "rt-priority" ) > 0 )
708 int i_error, i_policy;
709 struct sched_param param;
711 memset( ¶m, 0, sizeof(struct sched_param) );
712 if( config_GetType( p_this, "rt-offset" ) )
713 i_priority += config_GetInt( p_this, "rt-offset" );
714 if( i_priority <= 0 )
716 param.sched_priority = (-1) * i_priority;
717 i_policy = SCHED_OTHER;
721 param.sched_priority = i_priority;
724 if( (i_error = pthread_setschedparam( p_priv->thread_id,
725 i_policy, ¶m )) )
728 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
734 #elif defined( WIN32 ) || defined( UNDER_CE )
735 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
737 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
739 msg_Warn( p_this, "couldn't set a faster priority" );
748 /*****************************************************************************
749 * vlc_thread_join: wait until a thread exits, inner version
750 *****************************************************************************/
751 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
753 vlc_object_internals_t *p_priv = vlc_internals( p_this );
756 #if defined( LIBVLC_USE_PTHREAD )
757 /* Make sure we do return if we are calling vlc_thread_join()
758 * from the joined thread */
759 if (pthread_equal (pthread_self (), p_priv->thread_id))
761 msg_Warn (p_this, "joining the active thread (VLC might crash)");
762 i_ret = pthread_detach (p_priv->thread_id);
765 i_ret = vlc_join (p_priv->thread_id, NULL);
767 #elif defined( UNDER_CE ) || defined( WIN32 )
769 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
770 int64_t real_time, kernel_time, user_time;
772 if( ! DuplicateHandle(GetCurrentProcess(),
773 p_priv->thread_id->handle,
778 DUPLICATE_SAME_ACCESS) )
780 p_priv->b_thread = false;
781 i_ret = GetLastError();
785 vlc_join( p_priv->thread_id, NULL );
787 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
790 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
791 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
795 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
796 kernel_ft.dwLowDateTime) / 10;
799 ((((int64_t)user_ft.dwHighDateTime)<<32)|
800 user_ft.dwLowDateTime) / 10;
802 msg_Dbg( p_this, "thread times: "
803 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
804 real_time/60/1000000,
805 (double)((real_time%(60*1000000))/1000000.0),
806 kernel_time/60/1000000,
807 (double)((kernel_time%(60*1000000))/1000000.0),
808 user_time/60/1000000,
809 (double)((user_time%(60*1000000))/1000000.0) );
811 CloseHandle( hThread );
815 i_ret = vlc_join( p_priv->thread_id, NULL );
822 msg_Err( p_this, "thread_join(%lu) failed at %s:%d (%m)",
823 (unsigned long)p_priv->thread_id, psz_file, i_line );
826 msg_Dbg( p_this, "thread %lu joined (%s:%d)",
827 (unsigned long)p_priv->thread_id, psz_file, i_line );
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);