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 *****************************************************************************/
39 #define VLC_THREADS_UNINITIALIZED 0
40 #define VLC_THREADS_PENDING 1
41 #define VLC_THREADS_ERROR 2
42 #define VLC_THREADS_READY 3
44 /*****************************************************************************
45 * Global mutex for lazy initialization of the threads system
46 *****************************************************************************/
47 static volatile unsigned i_initializations = 0;
48 static volatile int i_status = VLC_THREADS_UNINITIALIZED;
49 static vlc_object_t *p_root;
51 #if defined( UNDER_CE )
52 #elif defined( WIN32 )
55 ** On Windows NT/2K/XP we use a slow mutex implementation but which
56 ** allows us to correctly implement condition variables.
57 ** You can also use the faster Win9x implementation but you might
58 ** experience problems with it.
60 static bool b_fast_mutex = false;
62 ** On Windows 9x/Me you can use a fast but incorrect condition variables
63 ** implementation (more precisely there is a possibility for a race
64 ** condition to happen).
65 ** However it is possible to use slower alternatives which are more robust.
66 ** Currently you can choose between implementation 0 (which is the
67 ** fastest but slightly incorrect), 1 (default) and 2.
69 static int i_win9x_cv = 1;
71 #elif defined( HAVE_KERNEL_SCHEDULER_H )
72 #elif defined( LIBVLC_USE_PTHREAD )
73 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
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 ();
87 /*****************************************************************************
88 * vlc_thread_fatal: Report an error from the threading layer
89 *****************************************************************************
90 * This is mostly meant for debugging.
91 *****************************************************************************/
92 void vlc_pthread_fatal (const char *action, int error,
93 const char *file, unsigned line)
95 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
96 action, vlc_threadid (), file, line, error);
99 /* Sometimes strerror_r() crashes too, so make sure we print an error
100 * message before we invoke it */
102 /* Avoid the strerror_r() prototype brain damage in glibc */
104 fprintf (stderr, " Error message: %m\n");
109 switch (strerror_r (error, buf, sizeof (buf)))
114 case ERANGE: /* should never happen */
115 msg = "unknwon (too big to display)";
118 msg = "unknown (invalid error number)";
121 fprintf (stderr, " Error message: %s\n", msg);
130 /*****************************************************************************
131 * vlc_threads_init: initialize threads system
132 *****************************************************************************
133 * This function requires lazy initialization of a global lock in order to
134 * keep the library really thread-safe. Some architectures don't support this
135 * and thus do not guarantee the complete reentrancy.
136 *****************************************************************************/
137 int __vlc_threads_init( vlc_object_t *p_this )
139 libvlc_global_data_t *p_libvlc_global = (libvlc_global_data_t *)p_this;
140 int i_ret = VLC_SUCCESS;
142 /* If we have lazy mutex initialization, use it. Otherwise, we just
143 * hope nothing wrong happens. */
144 #if defined( UNDER_CE )
145 #elif defined( WIN32 )
146 if( IsDebuggerPresent() )
148 /* SignalObjectAndWait() is problematic under a debugger */
152 #elif defined( HAVE_KERNEL_SCHEDULER_H )
153 #elif defined( LIBVLC_USE_PTHREAD )
154 pthread_mutex_lock( &once_mutex );
157 if( i_status == VLC_THREADS_UNINITIALIZED )
159 i_status = VLC_THREADS_PENDING;
161 /* We should be safe now. Do all the initialization stuff we want. */
162 p_libvlc_global->b_ready = false;
164 p_root = vlc_custom_create( VLC_OBJECT(p_libvlc_global), 0,
165 VLC_OBJECT_GLOBAL, "global" );
171 i_status = VLC_THREADS_ERROR;
176 i_status = VLC_THREADS_READY;
179 vlc_threadvar_create( p_root, &msg_context_global_key );
183 /* Just increment the initialization count */
187 /* If we have lazy mutex initialization support, unlock the mutex;
188 * otherwize, do a naive wait loop. */
189 #if defined( UNDER_CE )
190 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
191 #elif defined( WIN32 )
192 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
193 #elif defined( HAVE_KERNEL_SCHEDULER_H )
194 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
195 #elif defined( LIBVLC_USE_PTHREAD )
196 pthread_mutex_unlock( &once_mutex );
199 if( i_status != VLC_THREADS_READY )
207 /*****************************************************************************
208 * vlc_threads_end: stop threads system
209 *****************************************************************************
210 * FIXME: This function is far from being threadsafe.
211 *****************************************************************************/
212 int __vlc_threads_end( vlc_object_t *p_this )
215 #if defined( UNDER_CE )
216 #elif defined( WIN32 )
217 #elif defined( HAVE_KERNEL_SCHEDULER_H )
218 #elif defined( LIBVLC_USE_PTHREAD )
219 pthread_mutex_lock( &once_mutex );
222 if( i_initializations == 0 )
226 if( i_initializations == 0 )
228 i_status = VLC_THREADS_UNINITIALIZED;
229 vlc_object_release( p_root );
232 #if defined( UNDER_CE )
233 #elif defined( WIN32 )
234 #elif defined( HAVE_KERNEL_SCHEDULER_H )
235 #elif defined( LIBVLC_USE_PTHREAD )
236 pthread_mutex_unlock( &once_mutex );
242 /* This is not prototyped under Linux, though it exists. */
243 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
246 /*****************************************************************************
247 * vlc_mutex_init: initialize a mutex
248 *****************************************************************************/
249 int __vlc_mutex_init( vlc_mutex_t *p_mutex )
251 #if defined( UNDER_CE )
252 InitializeCriticalSection( &p_mutex->csection );
255 #elif defined( WIN32 )
258 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
259 return ( p_mutex->mutex != NULL ? 0 : 1 );
263 p_mutex->mutex = NULL;
264 InitializeCriticalSection( &p_mutex->csection );
268 #elif defined( HAVE_KERNEL_SCHEDULER_H )
269 /* check the arguments and whether it's already been initialized */
270 if( p_mutex == NULL )
275 if( p_mutex->init == 9999 )
280 p_mutex->lock = create_sem( 1, "BeMutex" );
281 if( p_mutex->lock < B_NO_ERROR )
286 p_mutex->init = 9999;
289 #elif defined( LIBVLC_USE_PTHREAD )
290 pthread_mutexattr_t attr;
293 pthread_mutexattr_init( &attr );
296 /* Create error-checking mutex to detect problems more easily. */
297 # if defined(SYS_LINUX)
298 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
300 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
303 i_result = pthread_mutex_init( p_mutex, &attr );
304 pthread_mutexattr_destroy( &attr );
309 /*****************************************************************************
310 * vlc_mutex_init: initialize a recursive mutex (Do not use)
311 *****************************************************************************/
312 int __vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
315 /* Create mutex returns a recursive mutex */
316 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
317 return ( p_mutex->mutex != NULL ? 0 : 1 );
318 #elif defined( LIBVLC_USE_PTHREAD )
319 pthread_mutexattr_t attr;
322 pthread_mutexattr_init( &attr );
324 /* Create error-checking mutex to detect problems more easily. */
325 # if defined(SYS_LINUX)
326 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
328 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
331 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
332 i_result = pthread_mutex_init( p_mutex, &attr );
333 pthread_mutexattr_destroy( &attr );
336 # error Unimplemented!
341 /*****************************************************************************
342 * vlc_mutex_destroy: destroy a mutex, inner version
343 *****************************************************************************/
344 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
346 #if defined( UNDER_CE )
347 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
349 DeleteCriticalSection( &p_mutex->csection );
351 #elif defined( WIN32 )
352 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
355 CloseHandle( p_mutex->mutex );
357 DeleteCriticalSection( &p_mutex->csection );
359 #elif defined( HAVE_KERNEL_SCHEDULER_H )
360 if( p_mutex->init == 9999 )
361 delete_sem( p_mutex->lock );
365 #elif defined( LIBVLC_USE_PTHREAD )
366 int val = pthread_mutex_destroy( p_mutex );
367 VLC_THREAD_ASSERT ("destroying mutex");
372 /*****************************************************************************
373 * vlc_cond_init: initialize a condition
374 *****************************************************************************/
375 int __vlc_cond_init( vlc_cond_t *p_condvar )
377 #if defined( UNDER_CE )
378 /* Initialize counter */
379 p_condvar->i_waiting_threads = 0;
381 /* Create an auto-reset event. */
382 p_condvar->event = CreateEvent( NULL, /* no security */
383 FALSE, /* auto-reset event */
384 FALSE, /* start non-signaled */
385 NULL ); /* unnamed */
386 return !p_condvar->event;
388 #elif defined( WIN32 )
389 /* Initialize counter */
390 p_condvar->i_waiting_threads = 0;
393 p_condvar->i_win9x_cv = i_win9x_cv;
395 if( !b_fast_mutex || p_condvar->i_win9x_cv == 0 )
397 /* Create an auto-reset event. */
398 p_condvar->event = CreateEvent( NULL, /* no security */
399 FALSE, /* auto-reset event */
400 FALSE, /* start non-signaled */
401 NULL ); /* unnamed */
403 p_condvar->semaphore = NULL;
404 return !p_condvar->event;
408 p_condvar->semaphore = CreateSemaphore( NULL, /* no security */
409 0, /* initial count */
410 0x7fffffff, /* max count */
411 NULL ); /* unnamed */
413 if( p_condvar->i_win9x_cv == 1 )
414 /* Create a manual-reset event initially signaled. */
415 p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
417 /* Create a auto-reset event. */
418 p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
420 InitializeCriticalSection( &p_condvar->csection );
422 return !p_condvar->semaphore || !p_condvar->event;
425 #elif defined( HAVE_KERNEL_SCHEDULER_H )
431 if( p_condvar->init == 9999 )
436 p_condvar->thread = -1;
437 p_condvar->init = 9999;
440 #elif defined( LIBVLC_USE_PTHREAD )
441 pthread_condattr_t attr;
444 ret = pthread_condattr_init (&attr);
448 # if !defined (_POSIX_CLOCK_SELECTION)
449 /* Fairly outdated POSIX support (that was defined in 2001) */
450 # define _POSIX_CLOCK_SELECTION (-1)
452 # if (_POSIX_CLOCK_SELECTION >= 0)
453 /* NOTE: This must be the same clock as the one in mtime.c */
454 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
457 ret = pthread_cond_init (p_condvar, &attr);
458 pthread_condattr_destroy (&attr);
464 /*****************************************************************************
465 * vlc_cond_destroy: destroy a condition, inner version
466 *****************************************************************************/
467 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
469 #if defined( UNDER_CE )
470 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
472 CloseHandle( p_condvar->event );
474 #elif defined( WIN32 )
475 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
477 if( !p_condvar->semaphore )
478 CloseHandle( p_condvar->event );
481 CloseHandle( p_condvar->event );
482 CloseHandle( p_condvar->semaphore );
485 if( p_condvar->semaphore != NULL )
486 DeleteCriticalSection( &p_condvar->csection );
488 #elif defined( HAVE_KERNEL_SCHEDULER_H )
491 #elif defined( LIBVLC_USE_PTHREAD )
492 int val = pthread_cond_destroy( p_condvar );
493 VLC_THREAD_ASSERT ("destroying condition");
498 /*****************************************************************************
499 * vlc_tls_create: create a thread-local variable
500 *****************************************************************************/
501 int __vlc_threadvar_create( vlc_threadvar_t *p_tls )
505 #if defined( HAVE_KERNEL_SCHEDULER_H )
506 # error Unimplemented!
507 #elif defined( UNDER_CE ) || defined( WIN32 )
508 #elif defined( WIN32 )
510 i_ret = (*p_tls == INVALID_HANDLE_VALUE) ? EAGAIN : 0;
512 #elif defined( LIBVLC_USE_PTHREAD )
513 i_ret = pthread_key_create( p_tls, NULL );
518 /*****************************************************************************
519 * vlc_thread_create: create a thread, inner version
520 *****************************************************************************
521 * Note that i_priority is only taken into account on platforms supporting
522 * userland real-time priority threads.
523 *****************************************************************************/
524 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
525 const char *psz_name, void * ( *func ) ( void * ),
526 int i_priority, bool b_wait )
529 void *p_data = (void *)p_this;
530 vlc_object_internals_t *p_priv = p_this->p_internals;
532 vlc_mutex_lock( &p_this->object_lock );
534 #if defined( WIN32 ) || defined( UNDER_CE )
536 /* When using the MSVCRT C library you have to use the _beginthreadex
537 * function instead of CreateThread, otherwise you'll end up with
538 * memory leaks and the signal functions not working (see Microsoft
539 * Knowledge Base, article 104641) */
540 #if defined( UNDER_CE )
542 HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
543 (LPVOID)p_data, CREATE_SUSPENDED,
547 uintptr_t hThread = _beginthreadex( NULL, 0,
548 (LPTHREAD_START_ROUTINE)func,
549 (void*)p_data, CREATE_SUSPENDED,
552 p_priv->thread_id.id = (DWORD)threadId;
553 p_priv->thread_id.hThread = (HANDLE)hThread;
554 ResumeThread((HANDLE)hThread);
557 i_ret = ( p_priv->thread_id.hThread ? 0 : 1 );
559 if( !i_ret && i_priority )
561 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
563 msg_Warn( p_this, "couldn't set a faster priority" );
568 #elif defined( HAVE_KERNEL_SCHEDULER_H )
569 p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
570 i_priority, p_data );
571 i_ret = resume_thread( p_priv->thread_id );
573 #elif defined( LIBVLC_USE_PTHREAD )
574 i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
577 if( config_GetInt( p_this, "rt-priority" ) )
580 int i_error, i_policy;
581 struct sched_param param;
583 memset( ¶m, 0, sizeof(struct sched_param) );
584 if( config_GetType( p_this, "rt-offset" ) )
586 i_priority += config_GetInt( p_this, "rt-offset" );
588 if( i_priority <= 0 )
590 param.sched_priority = (-1) * i_priority;
591 i_policy = SCHED_OTHER;
595 param.sched_priority = i_priority;
598 if( (i_error = pthread_setschedparam( p_priv->thread_id,
599 i_policy, ¶m )) )
602 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
620 msg_Dbg( p_this, "waiting for thread completion" );
621 vlc_object_wait( p_this );
624 p_priv->b_thread = true;
626 #if defined( WIN32 ) || defined( UNDER_CE )
627 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
628 (unsigned int)p_priv->thread_id.id, psz_name,
629 i_priority, psz_file, i_line );
631 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
632 (unsigned int)p_priv->thread_id, psz_name, i_priority,
637 vlc_mutex_unlock( &p_this->object_lock );
642 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
643 psz_name, psz_file, i_line );
644 vlc_mutex_unlock( &p_this->object_lock );
650 /*****************************************************************************
651 * vlc_thread_set_priority: set the priority of the current thread when we
652 * couldn't set it in vlc_thread_create (for instance for the main thread)
653 *****************************************************************************/
654 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
655 int i_line, int i_priority )
657 vlc_object_internals_t *p_priv = p_this->p_internals;
658 #if defined( WIN32 ) || defined( UNDER_CE )
659 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
661 if( !p_priv->thread_id.hThread )
662 p_priv->thread_id.hThread = GetCurrentThread();
663 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
665 msg_Warn( p_this, "couldn't set a faster priority" );
669 #elif defined( LIBVLC_USE_PTHREAD )
671 if( config_GetInt( p_this, "rt-priority" ) > 0 )
674 int i_error, i_policy;
675 struct sched_param param;
677 memset( ¶m, 0, sizeof(struct sched_param) );
678 if( config_GetType( p_this, "rt-offset" ) )
680 i_priority += config_GetInt( p_this, "rt-offset" );
682 if( i_priority <= 0 )
684 param.sched_priority = (-1) * i_priority;
685 i_policy = SCHED_OTHER;
689 param.sched_priority = i_priority;
692 if( !p_priv->thread_id )
693 p_priv->thread_id = pthread_self();
694 if( (i_error = pthread_setschedparam( p_priv->thread_id,
695 i_policy, ¶m )) )
698 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
708 /*****************************************************************************
709 * vlc_thread_ready: tell the parent thread we were successfully spawned
710 *****************************************************************************/
711 void __vlc_thread_ready( vlc_object_t *p_this )
713 vlc_object_signal( p_this );
716 /*****************************************************************************
717 * vlc_thread_join: wait until a thread exits, inner version
718 *****************************************************************************/
719 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
721 vlc_object_internals_t *p_priv = p_this->p_internals;
723 #if defined( UNDER_CE ) || defined( WIN32 )
725 BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
726 FILETIME*, FILETIME* );
727 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
728 int64_t real_time, kernel_time, user_time;
732 ** object will close its thread handle when destroyed, duplicate it here
733 ** to be on the safe side
735 if( ! DuplicateHandle(GetCurrentProcess(),
736 p_priv->thread_id.hThread,
741 DUPLICATE_SAME_ACCESS) )
743 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%u)",
744 (unsigned int)p_priv->thread_id.id,
745 psz_file, i_line, (unsigned int)GetLastError() );
746 p_priv->b_thread = false;
750 WaitForSingleObject( hThread, INFINITE );
752 msg_Dbg( p_this, "thread %u joined (%s:%d)",
753 (unsigned int)p_priv->thread_id.id,
755 #if defined( UNDER_CE )
756 hmodule = GetModuleHandle( _T("COREDLL") );
758 hmodule = GetModuleHandle( _T("KERNEL32") );
760 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
761 FILETIME*, FILETIME* ))
762 GetProcAddress( hmodule, _T("GetThreadTimes") );
764 if( OurGetThreadTimes &&
765 OurGetThreadTimes( hThread,
766 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
769 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
770 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
774 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
775 kernel_ft.dwLowDateTime) / 10;
778 ((((int64_t)user_ft.dwHighDateTime)<<32)|
779 user_ft.dwLowDateTime) / 10;
781 msg_Dbg( p_this, "thread times: "
782 "real "I64Fd"m%fs, kernel "I64Fd"m%fs, user "I64Fd"m%fs",
783 real_time/60/1000000,
784 (double)((real_time%(60*1000000))/1000000.0),
785 kernel_time/60/1000000,
786 (double)((kernel_time%(60*1000000))/1000000.0),
787 user_time/60/1000000,
788 (double)((user_time%(60*1000000))/1000000.0) );
790 CloseHandle( hThread );
792 #else /* !defined(WIN32) */
796 #if defined( HAVE_KERNEL_SCHEDULER_H )
798 i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
800 #elif defined( LIBVLC_USE_PTHREAD )
801 /* Make sure we do return if we are calling vlc_thread_join()
802 * from the joined thread */
803 if (pthread_equal (pthread_self (), p_priv->thread_id))
804 i_ret = pthread_detach (p_priv->thread_id);
806 i_ret = pthread_join (p_priv->thread_id, NULL);
812 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%m)",
813 (unsigned int)p_priv->thread_id, psz_file, i_line );
817 msg_Dbg( p_this, "thread %u joined (%s:%d)",
818 (unsigned int)p_priv->thread_id, psz_file, i_line );
823 p_priv->b_thread = false;