1 /*****************************************************************************
2 * threads.c : threads implementation for the VideoLAN client
3 *****************************************************************************
4 * Copyright (C) 1999-2007 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 *****************************************************************************/
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 )
51 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
55 * Global process-wide VLC object.
56 * Contains inter-instance data, such as the module cache and global mutexes.
58 static libvlc_global_data_t *p_root;
60 libvlc_global_data_t *vlc_global( void )
62 assert( i_initializations > 0 );
67 * Object running the current thread
69 static vlc_threadvar_t thread_object_key;
71 vlc_object_t *vlc_threadobj (void)
73 return vlc_threadvar_get (&thread_object_key);
76 vlc_threadvar_t msg_context_global_key;
78 #if defined(LIBVLC_USE_PTHREAD)
79 static inline unsigned long vlc_threadid (void)
81 union { pthread_t th; unsigned long int i; } v = { };
82 v.th = pthread_self ();
86 #if defined(__GLIBC__) || defined(__APPLE__)
87 # include <execinfo.h>
90 /*****************************************************************************
91 * vlc_thread_fatal: Report an error from the threading layer
92 *****************************************************************************
93 * This is mostly meant for debugging.
94 *****************************************************************************/
95 void vlc_pthread_fatal (const char *action, int error,
96 const char *file, unsigned line)
98 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
99 action, vlc_threadid (), file, line, error);
102 /* Sometimes strerror_r() crashes too, so make sure we print an error
103 * message before we invoke it */
105 /* Avoid the strerror_r() prototype brain damage in glibc */
107 dprintf (2, " Error message: %m at:\n");
112 switch (strerror_r (error, buf, sizeof (buf)))
117 case ERANGE: /* should never happen */
118 msg = "unknwon (too big to display)";
121 msg = "unknown (invalid error number)";
124 fprintf (stderr, " Error message: %s\n", msg);
128 #if defined(__GLIBC__) || defined(__APPLE__)
130 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
131 backtrace_symbols_fd (stack, len, 2);
137 void vlc_pthread_fatal (const char *action, int error,
138 const char *file, unsigned line)
140 (void)action; (void)error; (void)file; (void)line;
145 /*****************************************************************************
146 * vlc_threads_init: initialize threads system
147 *****************************************************************************
148 * This function requires lazy initialization of a global lock in order to
149 * keep the library really thread-safe. Some architectures don't support this
150 * and thus do not guarantee the complete reentrancy.
151 *****************************************************************************/
152 int vlc_threads_init( void )
154 int i_ret = VLC_SUCCESS;
156 /* If we have lazy mutex initialization, use it. Otherwise, we just
157 * hope nothing wrong happens. */
158 #if defined( LIBVLC_USE_PTHREAD )
159 pthread_mutex_lock( &once_mutex );
162 if( i_initializations == 0 )
164 p_root = vlc_custom_create( NULL, sizeof( *p_root ),
165 VLC_OBJECT_GENERIC, "root" );
172 /* We should be safe now. Do all the initialization stuff we want. */
173 vlc_threadvar_create( &thread_object_key, NULL );
174 vlc_threadvar_create( &msg_context_global_key, msg_StackDestroy );
179 /* If we have lazy mutex initialization support, unlock the mutex.
180 * Otherwize, we are screwed. */
181 #if defined( LIBVLC_USE_PTHREAD )
182 pthread_mutex_unlock( &once_mutex );
188 /*****************************************************************************
189 * vlc_threads_end: stop threads system
190 *****************************************************************************
191 * FIXME: This function is far from being threadsafe.
192 *****************************************************************************/
193 void vlc_threads_end( void )
195 #if defined( LIBVLC_USE_PTHREAD )
196 pthread_mutex_lock( &once_mutex );
199 assert( i_initializations > 0 );
201 if( i_initializations == 1 )
203 vlc_object_release( p_root );
204 vlc_threadvar_delete( &msg_context_global_key );
205 vlc_threadvar_delete( &thread_object_key );
209 #if defined( LIBVLC_USE_PTHREAD )
210 pthread_mutex_unlock( &once_mutex );
214 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
215 /* This is not prototyped under glibc, though it exists. */
216 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
219 /*****************************************************************************
220 * vlc_mutex_init: initialize a mutex
221 *****************************************************************************/
222 int vlc_mutex_init( vlc_mutex_t *p_mutex )
224 #if defined( LIBVLC_USE_PTHREAD )
225 pthread_mutexattr_t attr;
228 pthread_mutexattr_init( &attr );
231 /* Create error-checking mutex to detect problems more easily. */
232 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
233 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
235 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
238 i_result = pthread_mutex_init( p_mutex, &attr );
239 pthread_mutexattr_destroy( &attr );
241 #elif defined( UNDER_CE )
242 InitializeCriticalSection( &p_mutex->csection );
245 #elif defined( WIN32 )
246 *p_mutex = CreateMutex( 0, FALSE, 0 );
247 return (*p_mutex != NULL) ? 0 : ENOMEM;
249 #elif defined( HAVE_KERNEL_SCHEDULER_H )
250 /* check the arguments and whether it's already been initialized */
251 if( p_mutex == NULL )
256 if( p_mutex->init == 9999 )
261 p_mutex->lock = create_sem( 1, "BeMutex" );
262 if( p_mutex->lock < B_NO_ERROR )
267 p_mutex->init = 9999;
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 );
320 #elif defined( HAVE_KERNEL_SCHEDULER_H )
321 if( p_mutex->init == 9999 )
322 delete_sem( p_mutex->lock );
329 /*****************************************************************************
330 * vlc_cond_init: initialize a condition
331 *****************************************************************************/
332 int __vlc_cond_init( vlc_cond_t *p_condvar )
334 #if defined( LIBVLC_USE_PTHREAD )
335 pthread_condattr_t attr;
338 ret = pthread_condattr_init (&attr);
342 # if !defined (_POSIX_CLOCK_SELECTION)
343 /* Fairly outdated POSIX support (that was defined in 2001) */
344 # define _POSIX_CLOCK_SELECTION (-1)
346 # if (_POSIX_CLOCK_SELECTION >= 0)
347 /* NOTE: This must be the same clock as the one in mtime.c */
348 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
351 ret = pthread_cond_init (p_condvar, &attr);
352 pthread_condattr_destroy (&attr);
355 #elif defined( UNDER_CE ) || defined( WIN32 )
356 /* Initialize counter */
357 p_condvar->i_waiting_threads = 0;
359 /* Create an auto-reset event. */
360 p_condvar->event = CreateEvent( NULL, /* no security */
361 FALSE, /* auto-reset event */
362 FALSE, /* start non-signaled */
363 NULL ); /* unnamed */
364 return !p_condvar->event;
366 #elif defined( HAVE_KERNEL_SCHEDULER_H )
372 if( p_condvar->init == 9999 )
377 p_condvar->thread = -1;
378 p_condvar->init = 9999;
384 /*****************************************************************************
385 * vlc_cond_destroy: destroy a condition, inner version
386 *****************************************************************************/
387 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
389 #if defined( LIBVLC_USE_PTHREAD )
390 int val = pthread_cond_destroy( p_condvar );
391 VLC_THREAD_ASSERT ("destroying condition");
393 #elif defined( UNDER_CE ) || defined( WIN32 )
394 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
396 CloseHandle( p_condvar->event );
398 #elif defined( HAVE_KERNEL_SCHEDULER_H )
404 /*****************************************************************************
405 * vlc_tls_create: create a thread-local variable
406 *****************************************************************************/
407 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
411 #if defined( LIBVLC_USE_PTHREAD )
412 i_ret = pthread_key_create( p_tls, destr );
413 #elif defined( UNDER_CE )
415 #elif defined( WIN32 )
417 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
419 # error Unimplemented!
424 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
426 #if defined( LIBVLC_USE_PTHREAD )
427 pthread_key_delete (*p_tls);
428 #elif defined( UNDER_CE )
429 #elif defined( WIN32 )
432 # error Unimplemented!
436 struct vlc_thread_boot
438 void * (*entry) (void *);
439 vlc_object_t *object;
442 #if defined (LIBVLC_USE_PTHREAD)
443 # define THREAD_RTYPE void *
444 # define THREAD_RVAL NULL
445 #elif defined (WIN32)
446 # define THREAD_RTYPE __stdcall unsigned
447 # define THREAD_RVAL 0
450 static THREAD_RTYPE thread_entry (void *data)
452 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
453 void *(*func) (void *) = ((struct vlc_thread_boot *)data)->entry;
456 vlc_threadvar_set (&thread_object_key, obj);
457 msg_Dbg (obj, "thread started");
459 msg_Dbg (obj, "thread ended");
463 /*****************************************************************************
464 * vlc_thread_create: create a thread, inner version
465 *****************************************************************************
466 * Note that i_priority is only taken into account on platforms supporting
467 * userland real-time priority threads.
468 *****************************************************************************/
469 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
470 const char *psz_name, void * ( *func ) ( void * ),
471 int i_priority, bool b_wait )
474 vlc_object_internals_t *p_priv = vlc_internals( p_this );
476 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
480 boot->object = p_this;
482 vlc_mutex_lock( &p_this->object_lock );
484 #if defined( LIBVLC_USE_PTHREAD )
485 sigset_t set, oldset;
487 /* We really don't want signals to (literaly) interrupt our blocking I/O
488 * system calls. SIGPIPE is especially bad, as it can be caused by remote
489 * peers through connected sockets. Generally, we cannot know which signals
490 * are handled by the main program. Also, external LibVLC bindings tend not
491 * to setup a proper signal mask before invoking LibVLC.
492 * Hence, we hereby block all signals, except those for which blocking is
493 * undefined, as listed below. Note that SIGKILL and SIGSTOP need not be
494 * listed (see the documentation for pthread_sigmask) here. */
496 sigdelset (&set, SIGFPE);
497 sigdelset (&set, SIGILL);
498 sigdelset (&set, SIGSEGV);
499 sigdelset (&set, SIGBUS);
500 pthread_sigmask (SIG_BLOCK, &set, &oldset);
502 i_ret = pthread_create( &p_priv->thread_id, NULL, thread_entry, boot );
503 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
506 if( config_GetInt( p_this, "rt-priority" ) > 0 )
509 int i_error, i_policy;
510 struct sched_param param;
512 memset( ¶m, 0, sizeof(struct sched_param) );
513 if( config_GetType( p_this, "rt-offset" ) )
514 i_priority += config_GetInt( p_this, "rt-offset" );
515 if( i_priority <= 0 )
517 param.sched_priority = (-1) * i_priority;
518 i_policy = SCHED_OTHER;
522 param.sched_priority = i_priority;
525 if( (i_error = pthread_setschedparam( p_priv->thread_id,
526 i_policy, ¶m )) )
529 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
539 #elif defined( WIN32 ) || defined( UNDER_CE )
541 /* When using the MSVCRT C library you have to use the _beginthreadex
542 * function instead of CreateThread, otherwise you'll end up with
543 * memory leaks and the signal functions not working (see Microsoft
544 * Knowledge Base, article 104641) */
545 #if defined( UNDER_CE )
546 HANDLE hThread = CreateThread( NULL, 0, thread_entry,
547 (LPVOID)boot, CREATE_SUSPENDED,
550 HANDLE hThread = (HANDLE)(uintptr_t)
551 _beginthreadex( NULL, 0, thread_entry, boot,
552 CREATE_SUSPENDED, NULL );
554 p_priv->thread_id = hThread;
555 ResumeThread(hThread);
558 i_ret = ( p_priv->thread_id ? 0 : errno );
560 if( !i_ret && i_priority )
562 if( !SetThreadPriority(p_priv->thread_id, i_priority) )
564 msg_Warn( p_this, "couldn't set a faster priority" );
569 #elif defined( HAVE_KERNEL_SCHEDULER_H )
570 p_priv->thread_id = spawn_thread( (thread_func)thread_entry, psz_name,
571 i_priority, p_data );
572 i_ret = resume_thread( p_priv->thread_id );
580 msg_Dbg( p_this, "waiting for thread completion" );
581 vlc_object_wait( p_this );
584 p_priv->b_thread = true;
585 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
586 (unsigned long)p_priv->thread_id, psz_name, i_priority,
592 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
593 psz_name, psz_file, i_line );
596 vlc_mutex_unlock( &p_this->object_lock );
600 /*****************************************************************************
601 * vlc_thread_set_priority: set the priority of the current thread when we
602 * couldn't set it in vlc_thread_create (for instance for the main thread)
603 *****************************************************************************/
604 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
605 int i_line, int i_priority )
607 vlc_object_internals_t *p_priv = vlc_internals( p_this );
609 #if defined( LIBVLC_USE_PTHREAD )
611 if( config_GetInt( p_this, "rt-priority" ) > 0 )
614 int i_error, i_policy;
615 struct sched_param param;
617 memset( ¶m, 0, sizeof(struct sched_param) );
618 if( config_GetType( p_this, "rt-offset" ) )
619 i_priority += config_GetInt( p_this, "rt-offset" );
620 if( i_priority <= 0 )
622 param.sched_priority = (-1) * i_priority;
623 i_policy = SCHED_OTHER;
627 param.sched_priority = i_priority;
630 if( !p_priv->thread_id )
631 p_priv->thread_id = pthread_self();
632 if( (i_error = pthread_setschedparam( p_priv->thread_id,
633 i_policy, ¶m )) )
636 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
642 #elif defined( WIN32 ) || defined( UNDER_CE )
643 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
645 if( !p_priv->thread_id )
646 p_priv->thread_id = GetCurrentThread();
647 if( !SetThreadPriority(p_priv->thread_id, i_priority) )
649 msg_Warn( p_this, "couldn't set a faster priority" );
658 /*****************************************************************************
659 * vlc_thread_ready: tell the parent thread we were successfully spawned
660 *****************************************************************************/
661 void __vlc_thread_ready( vlc_object_t *p_this )
663 vlc_object_signal( p_this );
666 /*****************************************************************************
667 * vlc_thread_join: wait until a thread exits, inner version
668 *****************************************************************************/
669 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
671 vlc_object_internals_t *p_priv = vlc_internals( p_this );
674 #if defined( LIBVLC_USE_PTHREAD )
675 /* Make sure we do return if we are calling vlc_thread_join()
676 * from the joined thread */
677 if (pthread_equal (pthread_self (), p_priv->thread_id))
678 i_ret = pthread_detach (p_priv->thread_id);
680 i_ret = pthread_join (p_priv->thread_id, NULL);
682 #elif defined( UNDER_CE ) || defined( WIN32 )
684 BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
685 FILETIME*, FILETIME* );
686 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
687 int64_t real_time, kernel_time, user_time;
691 ** object will close its thread handle when destroyed, duplicate it here
692 ** to be on the safe side
694 if( ! DuplicateHandle(GetCurrentProcess(),
700 DUPLICATE_SAME_ACCESS) )
702 p_priv->b_thread = false;
703 i_ret = GetLastError();
707 WaitForSingleObject( hThread, INFINITE );
709 #if defined( UNDER_CE )
710 hmodule = GetModuleHandle( _T("COREDLL") );
712 hmodule = GetModuleHandle( _T("KERNEL32") );
714 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
715 FILETIME*, FILETIME* ))
716 GetProcAddress( hmodule, _T("GetThreadTimes") );
718 if( OurGetThreadTimes &&
719 OurGetThreadTimes( hThread,
720 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
723 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
724 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
728 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
729 kernel_ft.dwLowDateTime) / 10;
732 ((((int64_t)user_ft.dwHighDateTime)<<32)|
733 user_ft.dwLowDateTime) / 10;
735 msg_Dbg( p_this, "thread times: "
736 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
737 real_time/60/1000000,
738 (double)((real_time%(60*1000000))/1000000.0),
739 kernel_time/60/1000000,
740 (double)((kernel_time%(60*1000000))/1000000.0),
741 user_time/60/1000000,
742 (double)((user_time%(60*1000000))/1000000.0) );
744 CloseHandle( hThread );
747 #elif defined( HAVE_KERNEL_SCHEDULER_H )
749 i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
756 msg_Err( p_this, "thread_join(%lu) failed at %s:%d (%m)",
757 (unsigned long)p_priv->thread_id, psz_file, i_line );
760 msg_Dbg( p_this, "thread %lu joined (%s:%d)",
761 (unsigned long)p_priv->thread_id, psz_file, i_line );
763 p_priv->b_thread = false;