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 )
292 /* Create error-checking mutex to detect problems more easily. */
293 pthread_mutexattr_t attr;
296 pthread_mutexattr_init( &attr );
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->mutex, &attr );
304 pthread_mutexattr_destroy( &attr );
308 return pthread_mutex_init( &p_mutex->mutex, NULL );
313 /*****************************************************************************
314 * vlc_mutex_init: initialize a recursive mutex (Do not use)
315 *****************************************************************************/
316 int __vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
319 /* Create mutex returns a recursive mutex */
320 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
321 return ( p_mutex->mutex != NULL ? 0 : 1 );
322 #elif defined( LIBVLC_USE_PTHREAD )
323 pthread_mutexattr_t attr;
326 pthread_mutexattr_init( &attr );
328 /* Create error-checking mutex to detect problems more easily. */
329 # if defined(SYS_LINUX)
330 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
332 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
335 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
336 i_result = pthread_mutex_init( &p_mutex->mutex, &attr );
337 pthread_mutexattr_destroy( &attr );
340 # error Unimplemented!
345 /*****************************************************************************
346 * vlc_mutex_destroy: destroy a mutex, inner version
347 *****************************************************************************/
348 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
350 #if defined( UNDER_CE )
351 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
353 DeleteCriticalSection( &p_mutex->csection );
355 #elif defined( WIN32 )
356 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
359 CloseHandle( p_mutex->mutex );
361 DeleteCriticalSection( &p_mutex->csection );
363 #elif defined( HAVE_KERNEL_SCHEDULER_H )
364 if( p_mutex->init == 9999 )
365 delete_sem( p_mutex->lock );
369 #elif defined( LIBVLC_USE_PTHREAD )
370 int val = pthread_mutex_destroy( &p_mutex->mutex );
371 VLC_THREAD_ASSERT ("destroying mutex");
376 /*****************************************************************************
377 * vlc_cond_init: initialize a condition
378 *****************************************************************************/
379 int __vlc_cond_init( vlc_cond_t *p_condvar )
381 #if defined( UNDER_CE )
382 /* Initialize counter */
383 p_condvar->i_waiting_threads = 0;
385 /* Create an auto-reset event. */
386 p_condvar->event = CreateEvent( NULL, /* no security */
387 FALSE, /* auto-reset event */
388 FALSE, /* start non-signaled */
389 NULL ); /* unnamed */
390 return !p_condvar->event;
392 #elif defined( WIN32 )
393 /* Initialize counter */
394 p_condvar->i_waiting_threads = 0;
397 p_condvar->i_win9x_cv = i_win9x_cv;
399 if( !b_fast_mutex || p_condvar->i_win9x_cv == 0 )
401 /* Create an auto-reset event. */
402 p_condvar->event = CreateEvent( NULL, /* no security */
403 FALSE, /* auto-reset event */
404 FALSE, /* start non-signaled */
405 NULL ); /* unnamed */
407 p_condvar->semaphore = NULL;
408 return !p_condvar->event;
412 p_condvar->semaphore = CreateSemaphore( NULL, /* no security */
413 0, /* initial count */
414 0x7fffffff, /* max count */
415 NULL ); /* unnamed */
417 if( p_condvar->i_win9x_cv == 1 )
418 /* Create a manual-reset event initially signaled. */
419 p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
421 /* Create a auto-reset event. */
422 p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
424 InitializeCriticalSection( &p_condvar->csection );
426 return !p_condvar->semaphore || !p_condvar->event;
429 #elif defined( HAVE_KERNEL_SCHEDULER_H )
435 if( p_condvar->init == 9999 )
440 p_condvar->thread = -1;
441 p_condvar->init = 9999;
444 #elif defined( LIBVLC_USE_PTHREAD )
445 pthread_condattr_t attr;
448 ret = pthread_condattr_init (&attr);
452 # if !defined (_POSIX_CLOCK_SELECTION)
453 /* Fairly outdated POSIX support (that was defined in 2001) */
454 # define _POSIX_CLOCK_SELECTION (-1)
456 # if (_POSIX_CLOCK_SELECTION >= 0)
457 /* NOTE: This must be the same clock as the one in mtime.c */
458 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
461 ret = pthread_cond_init (&p_condvar->cond, &attr);
462 pthread_condattr_destroy (&attr);
468 /*****************************************************************************
469 * vlc_cond_destroy: destroy a condition, inner version
470 *****************************************************************************/
471 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
473 #if defined( UNDER_CE )
474 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
476 CloseHandle( p_condvar->event );
478 #elif defined( WIN32 )
479 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
481 if( !p_condvar->semaphore )
482 CloseHandle( p_condvar->event );
485 CloseHandle( p_condvar->event );
486 CloseHandle( p_condvar->semaphore );
489 if( p_condvar->semaphore != NULL )
490 DeleteCriticalSection( &p_condvar->csection );
492 #elif defined( HAVE_KERNEL_SCHEDULER_H )
495 #elif defined( LIBVLC_USE_PTHREAD )
496 int val = pthread_cond_destroy( &p_condvar->cond );
497 VLC_THREAD_ASSERT ("destroying condition");
502 /*****************************************************************************
503 * vlc_tls_create: create a thread-local variable
504 *****************************************************************************/
505 int __vlc_threadvar_create( vlc_threadvar_t *p_tls )
509 #if defined( HAVE_KERNEL_SCHEDULER_H )
510 # error Unimplemented!
511 #elif defined( UNDER_CE ) || defined( WIN32 )
512 #elif defined( WIN32 )
513 p_tls->handle = TlsAlloc();
514 i_ret = !( p_tls->handle == 0xFFFFFFFF );
516 #elif defined( LIBVLC_USE_PTHREAD )
517 i_ret = pthread_key_create( &p_tls->handle, NULL );
522 /*****************************************************************************
523 * vlc_thread_create: create a thread, inner version
524 *****************************************************************************
525 * Note that i_priority is only taken into account on platforms supporting
526 * userland real-time priority threads.
527 *****************************************************************************/
528 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
529 const char *psz_name, void * ( *func ) ( void * ),
530 int i_priority, bool b_wait )
533 void *p_data = (void *)p_this;
534 vlc_object_internals_t *p_priv = p_this->p_internals;
536 vlc_mutex_lock( &p_this->object_lock );
538 #if defined( WIN32 ) || defined( UNDER_CE )
540 /* When using the MSVCRT C library you have to use the _beginthreadex
541 * function instead of CreateThread, otherwise you'll end up with
542 * memory leaks and the signal functions not working (see Microsoft
543 * Knowledge Base, article 104641) */
544 #if defined( UNDER_CE )
546 HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
547 (LPVOID)p_data, CREATE_SUSPENDED,
551 uintptr_t hThread = _beginthreadex( NULL, 0,
552 (LPTHREAD_START_ROUTINE)func,
553 (void*)p_data, CREATE_SUSPENDED,
556 p_priv->thread_id.id = (DWORD)threadId;
557 p_priv->thread_id.hThread = (HANDLE)hThread;
558 ResumeThread((HANDLE)hThread);
561 i_ret = ( p_priv->thread_id.hThread ? 0 : 1 );
563 if( !i_ret && i_priority )
565 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
567 msg_Warn( p_this, "couldn't set a faster priority" );
572 #elif defined( HAVE_KERNEL_SCHEDULER_H )
573 p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
574 i_priority, p_data );
575 i_ret = resume_thread( p_priv->thread_id );
577 #elif defined( LIBVLC_USE_PTHREAD )
578 i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
581 if( config_GetInt( p_this, "rt-priority" ) )
584 int i_error, i_policy;
585 struct sched_param param;
587 memset( ¶m, 0, sizeof(struct sched_param) );
588 if( config_GetType( p_this, "rt-offset" ) )
590 i_priority += config_GetInt( p_this, "rt-offset" );
592 if( i_priority <= 0 )
594 param.sched_priority = (-1) * i_priority;
595 i_policy = SCHED_OTHER;
599 param.sched_priority = i_priority;
602 if( (i_error = pthread_setschedparam( p_priv->thread_id,
603 i_policy, ¶m )) )
606 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
624 msg_Dbg( p_this, "waiting for thread completion" );
625 vlc_object_wait( p_this );
628 p_priv->b_thread = true;
630 #if defined( WIN32 ) || defined( UNDER_CE )
631 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
632 (unsigned int)p_priv->thread_id.id, psz_name,
633 i_priority, psz_file, i_line );
635 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
636 (unsigned int)p_priv->thread_id, psz_name, i_priority,
641 vlc_mutex_unlock( &p_this->object_lock );
646 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
647 psz_name, psz_file, i_line );
648 vlc_mutex_unlock( &p_this->object_lock );
654 /*****************************************************************************
655 * vlc_thread_set_priority: set the priority of the current thread when we
656 * couldn't set it in vlc_thread_create (for instance for the main thread)
657 *****************************************************************************/
658 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
659 int i_line, int i_priority )
661 vlc_object_internals_t *p_priv = p_this->p_internals;
662 #if defined( WIN32 ) || defined( UNDER_CE )
663 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
665 if( !p_priv->thread_id.hThread )
666 p_priv->thread_id.hThread = GetCurrentThread();
667 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
669 msg_Warn( p_this, "couldn't set a faster priority" );
673 #elif defined( LIBVLC_USE_PTHREAD )
675 if( config_GetInt( p_this, "rt-priority" ) > 0 )
678 int i_error, i_policy;
679 struct sched_param param;
681 memset( ¶m, 0, sizeof(struct sched_param) );
682 if( config_GetType( p_this, "rt-offset" ) )
684 i_priority += config_GetInt( p_this, "rt-offset" );
686 if( i_priority <= 0 )
688 param.sched_priority = (-1) * i_priority;
689 i_policy = SCHED_OTHER;
693 param.sched_priority = i_priority;
696 if( !p_priv->thread_id )
697 p_priv->thread_id = pthread_self();
698 if( (i_error = pthread_setschedparam( p_priv->thread_id,
699 i_policy, ¶m )) )
702 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
712 /*****************************************************************************
713 * vlc_thread_ready: tell the parent thread we were successfully spawned
714 *****************************************************************************/
715 void __vlc_thread_ready( vlc_object_t *p_this )
717 vlc_object_signal( p_this );
720 /*****************************************************************************
721 * vlc_thread_join: wait until a thread exits, inner version
722 *****************************************************************************/
723 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
725 vlc_object_internals_t *p_priv = p_this->p_internals;
727 #if defined( UNDER_CE ) || defined( WIN32 )
729 BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
730 FILETIME*, FILETIME* );
731 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
732 int64_t real_time, kernel_time, user_time;
736 ** object will close its thread handle when destroyed, duplicate it here
737 ** to be on the safe side
739 if( ! DuplicateHandle(GetCurrentProcess(),
740 p_priv->thread_id.hThread,
745 DUPLICATE_SAME_ACCESS) )
747 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%u)",
748 (unsigned int)p_priv->thread_id.id,
749 psz_file, i_line, (unsigned int)GetLastError() );
750 p_priv->b_thread = false;
754 WaitForSingleObject( hThread, INFINITE );
756 msg_Dbg( p_this, "thread %u joined (%s:%d)",
757 (unsigned int)p_priv->thread_id.id,
759 #if defined( UNDER_CE )
760 hmodule = GetModuleHandle( _T("COREDLL") );
762 hmodule = GetModuleHandle( _T("KERNEL32") );
764 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
765 FILETIME*, FILETIME* ))
766 GetProcAddress( hmodule, _T("GetThreadTimes") );
768 if( OurGetThreadTimes &&
769 OurGetThreadTimes( hThread,
770 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
773 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
774 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
778 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
779 kernel_ft.dwLowDateTime) / 10;
782 ((((int64_t)user_ft.dwHighDateTime)<<32)|
783 user_ft.dwLowDateTime) / 10;
785 msg_Dbg( p_this, "thread times: "
786 "real "I64Fd"m%fs, kernel "I64Fd"m%fs, user "I64Fd"m%fs",
787 real_time/60/1000000,
788 (double)((real_time%(60*1000000))/1000000.0),
789 kernel_time/60/1000000,
790 (double)((kernel_time%(60*1000000))/1000000.0),
791 user_time/60/1000000,
792 (double)((user_time%(60*1000000))/1000000.0) );
794 CloseHandle( hThread );
796 #else /* !defined(WIN32) */
800 #if defined( HAVE_KERNEL_SCHEDULER_H )
802 i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
804 #elif defined( LIBVLC_USE_PTHREAD )
805 /* Make sure we do return if we are calling vlc_thread_join()
806 * from the joined thread */
807 if (pthread_equal (pthread_self (), p_priv->thread_id))
808 i_ret = pthread_detach (p_priv->thread_id);
810 i_ret = pthread_join (p_priv->thread_id, NULL);
816 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%m)",
817 (unsigned int)p_priv->thread_id, psz_file, i_line );
821 msg_Dbg( p_this, "thread %u joined (%s:%d)",
822 (unsigned int)p_priv->thread_id, psz_file, i_line );
827 p_priv->b_thread = false;