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 9x/Me you can use a fast but incorrect condition variables
56 ** implementation (more precisely there is a possibility for a race
57 ** condition to happen).
58 ** However it is possible to use slower alternatives which are more robust.
59 ** Currently you can choose between implementation 0 (which is the
60 ** fastest but slightly incorrect), 1 (default) and 2.
62 static int i_win9x_cv = 1;
64 #elif defined( HAVE_KERNEL_SCHEDULER_H )
65 #elif defined( LIBVLC_USE_PTHREAD )
66 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
69 vlc_threadvar_t msg_context_global_key;
71 #if defined(LIBVLC_USE_PTHREAD)
72 static inline unsigned long vlc_threadid (void)
74 union { pthread_t th; unsigned long int i; } v = { };
75 v.th = pthread_self ();
80 /*****************************************************************************
81 * vlc_thread_fatal: Report an error from the threading layer
82 *****************************************************************************
83 * This is mostly meant for debugging.
84 *****************************************************************************/
85 void vlc_pthread_fatal (const char *action, int error,
86 const char *file, unsigned line)
88 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
89 action, vlc_threadid (), file, line, error);
92 /* Sometimes strerror_r() crashes too, so make sure we print an error
93 * message before we invoke it */
95 /* Avoid the strerror_r() prototype brain damage in glibc */
97 fprintf (stderr, " Error message: %m\n");
102 switch (strerror_r (error, buf, sizeof (buf)))
107 case ERANGE: /* should never happen */
108 msg = "unknwon (too big to display)";
111 msg = "unknown (invalid error number)";
114 fprintf (stderr, " Error message: %s\n", msg);
123 /*****************************************************************************
124 * vlc_threads_init: initialize threads system
125 *****************************************************************************
126 * This function requires lazy initialization of a global lock in order to
127 * keep the library really thread-safe. Some architectures don't support this
128 * and thus do not guarantee the complete reentrancy.
129 *****************************************************************************/
130 int __vlc_threads_init( vlc_object_t *p_this )
132 libvlc_global_data_t *p_libvlc_global = (libvlc_global_data_t *)p_this;
133 int i_ret = VLC_SUCCESS;
135 /* If we have lazy mutex initialization, use it. Otherwise, we just
136 * hope nothing wrong happens. */
137 #if defined( UNDER_CE )
138 #elif defined( WIN32 )
139 if( IsDebuggerPresent() )
141 /* SignalObjectAndWait() is problematic under a debugger */
144 #elif defined( HAVE_KERNEL_SCHEDULER_H )
145 #elif defined( LIBVLC_USE_PTHREAD )
146 pthread_mutex_lock( &once_mutex );
149 if( i_status == VLC_THREADS_UNINITIALIZED )
151 i_status = VLC_THREADS_PENDING;
153 /* We should be safe now. Do all the initialization stuff we want. */
154 p_libvlc_global->b_ready = false;
156 p_root = vlc_custom_create( VLC_OBJECT(p_libvlc_global), 0,
157 VLC_OBJECT_GLOBAL, "global" );
163 i_status = VLC_THREADS_ERROR;
168 i_status = VLC_THREADS_READY;
171 vlc_threadvar_create( p_root, &msg_context_global_key );
175 /* Just increment the initialization count */
179 /* If we have lazy mutex initialization support, unlock the mutex;
180 * otherwize, do a naive wait loop. */
181 #if defined( UNDER_CE )
182 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
183 #elif defined( WIN32 )
184 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
185 #elif defined( HAVE_KERNEL_SCHEDULER_H )
186 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
187 #elif defined( LIBVLC_USE_PTHREAD )
188 pthread_mutex_unlock( &once_mutex );
191 if( i_status != VLC_THREADS_READY )
199 /*****************************************************************************
200 * vlc_threads_end: stop threads system
201 *****************************************************************************
202 * FIXME: This function is far from being threadsafe.
203 *****************************************************************************/
204 int __vlc_threads_end( vlc_object_t *p_this )
207 #if defined( UNDER_CE )
208 #elif defined( WIN32 )
209 #elif defined( HAVE_KERNEL_SCHEDULER_H )
210 #elif defined( LIBVLC_USE_PTHREAD )
211 pthread_mutex_lock( &once_mutex );
214 if( i_initializations == 0 )
218 if( i_initializations == 0 )
220 i_status = VLC_THREADS_UNINITIALIZED;
221 vlc_object_release( p_root );
224 #if defined( UNDER_CE )
225 #elif defined( WIN32 )
226 #elif defined( HAVE_KERNEL_SCHEDULER_H )
227 #elif defined( LIBVLC_USE_PTHREAD )
228 pthread_mutex_unlock( &once_mutex );
234 /* This is not prototyped under Linux, though it exists. */
235 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
238 /*****************************************************************************
239 * vlc_mutex_init: initialize a mutex
240 *****************************************************************************/
241 int __vlc_mutex_init( vlc_mutex_t *p_mutex )
243 #if defined( UNDER_CE )
244 InitializeCriticalSection( &p_mutex->csection );
247 #elif defined( WIN32 )
248 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
249 return ( p_mutex->mutex != NULL ? 0 : 1 );
251 #elif defined( HAVE_KERNEL_SCHEDULER_H )
252 /* check the arguments and whether it's already been initialized */
253 if( p_mutex == NULL )
258 if( p_mutex->init == 9999 )
263 p_mutex->lock = create_sem( 1, "BeMutex" );
264 if( p_mutex->lock < B_NO_ERROR )
269 p_mutex->init = 9999;
272 #elif defined( LIBVLC_USE_PTHREAD )
273 pthread_mutexattr_t attr;
276 pthread_mutexattr_init( &attr );
279 /* Create error-checking mutex to detect problems more easily. */
280 # if defined(SYS_LINUX)
281 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
283 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
286 i_result = pthread_mutex_init( p_mutex, &attr );
287 pthread_mutexattr_destroy( &attr );
292 /*****************************************************************************
293 * vlc_mutex_init: initialize a recursive mutex (Do not use)
294 *****************************************************************************/
295 int __vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
298 /* Create mutex returns a recursive mutex */
299 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
300 return ( p_mutex->mutex != NULL ? 0 : 1 );
301 #elif defined( LIBVLC_USE_PTHREAD )
302 pthread_mutexattr_t attr;
305 pthread_mutexattr_init( &attr );
307 /* Create error-checking mutex to detect problems more easily. */
308 # if defined(SYS_LINUX)
309 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
311 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
314 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
315 i_result = pthread_mutex_init( p_mutex, &attr );
316 pthread_mutexattr_destroy( &attr );
319 # error Unimplemented!
324 /*****************************************************************************
325 * vlc_mutex_destroy: destroy a mutex, inner version
326 *****************************************************************************/
327 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
329 #if defined( UNDER_CE )
330 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
332 DeleteCriticalSection( &p_mutex->csection );
334 #elif defined( WIN32 )
335 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
338 CloseHandle( p_mutex->mutex );
340 DeleteCriticalSection( &p_mutex->csection );
342 #elif defined( HAVE_KERNEL_SCHEDULER_H )
343 if( p_mutex->init == 9999 )
344 delete_sem( p_mutex->lock );
348 #elif defined( LIBVLC_USE_PTHREAD )
349 int val = pthread_mutex_destroy( p_mutex );
350 VLC_THREAD_ASSERT ("destroying mutex");
355 /*****************************************************************************
356 * vlc_cond_init: initialize a condition
357 *****************************************************************************/
358 int __vlc_cond_init( vlc_cond_t *p_condvar )
360 #if defined( UNDER_CE )
361 /* Initialize counter */
362 p_condvar->i_waiting_threads = 0;
364 /* Create an auto-reset event. */
365 p_condvar->event = CreateEvent( NULL, /* no security */
366 FALSE, /* auto-reset event */
367 FALSE, /* start non-signaled */
368 NULL ); /* unnamed */
369 return !p_condvar->event;
371 #elif defined( WIN32 )
372 /* Initialize counter */
373 p_condvar->i_waiting_threads = 0;
376 p_condvar->i_win9x_cv = i_win9x_cv;
378 /* Create an auto-reset event. */
379 p_condvar->event = CreateEvent( NULL, /* no security */
380 FALSE, /* auto-reset event */
381 FALSE, /* start non-signaled */
382 NULL ); /* unnamed */
384 p_condvar->semaphore = NULL;
385 return !p_condvar->event;
387 #elif defined( HAVE_KERNEL_SCHEDULER_H )
393 if( p_condvar->init == 9999 )
398 p_condvar->thread = -1;
399 p_condvar->init = 9999;
402 #elif defined( LIBVLC_USE_PTHREAD )
403 pthread_condattr_t attr;
406 ret = pthread_condattr_init (&attr);
410 # if !defined (_POSIX_CLOCK_SELECTION)
411 /* Fairly outdated POSIX support (that was defined in 2001) */
412 # define _POSIX_CLOCK_SELECTION (-1)
414 # if (_POSIX_CLOCK_SELECTION >= 0)
415 /* NOTE: This must be the same clock as the one in mtime.c */
416 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
419 ret = pthread_cond_init (p_condvar, &attr);
420 pthread_condattr_destroy (&attr);
426 /*****************************************************************************
427 * vlc_cond_destroy: destroy a condition, inner version
428 *****************************************************************************/
429 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
431 #if defined( UNDER_CE )
432 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
434 CloseHandle( p_condvar->event );
436 #elif defined( WIN32 )
437 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
439 if( !p_condvar->semaphore )
440 CloseHandle( p_condvar->event );
443 CloseHandle( p_condvar->event );
444 CloseHandle( p_condvar->semaphore );
447 if( p_condvar->semaphore != NULL )
448 DeleteCriticalSection( &p_condvar->csection );
450 #elif defined( HAVE_KERNEL_SCHEDULER_H )
453 #elif defined( LIBVLC_USE_PTHREAD )
454 int val = pthread_cond_destroy( p_condvar );
455 VLC_THREAD_ASSERT ("destroying condition");
460 /*****************************************************************************
461 * vlc_tls_create: create a thread-local variable
462 *****************************************************************************/
463 int __vlc_threadvar_create( vlc_threadvar_t *p_tls )
467 #if defined( HAVE_KERNEL_SCHEDULER_H )
468 # error Unimplemented!
469 #elif defined( UNDER_CE ) || defined( WIN32 )
470 #elif defined( WIN32 )
472 i_ret = (*p_tls == INVALID_HANDLE_VALUE) ? EAGAIN : 0;
474 #elif defined( LIBVLC_USE_PTHREAD )
475 i_ret = pthread_key_create( p_tls, NULL );
480 /*****************************************************************************
481 * vlc_thread_create: create a thread, inner version
482 *****************************************************************************
483 * Note that i_priority is only taken into account on platforms supporting
484 * userland real-time priority threads.
485 *****************************************************************************/
486 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
487 const char *psz_name, void * ( *func ) ( void * ),
488 int i_priority, bool b_wait )
491 void *p_data = (void *)p_this;
492 vlc_object_internals_t *p_priv = p_this->p_internals;
494 vlc_mutex_lock( &p_this->object_lock );
496 #if defined( WIN32 ) || defined( UNDER_CE )
498 /* When using the MSVCRT C library you have to use the _beginthreadex
499 * function instead of CreateThread, otherwise you'll end up with
500 * memory leaks and the signal functions not working (see Microsoft
501 * Knowledge Base, article 104641) */
502 #if defined( UNDER_CE )
504 HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
505 (LPVOID)p_data, CREATE_SUSPENDED,
509 uintptr_t hThread = _beginthreadex( NULL, 0,
510 (LPTHREAD_START_ROUTINE)func,
511 (void*)p_data, CREATE_SUSPENDED,
514 p_priv->thread_id.id = (DWORD)threadId;
515 p_priv->thread_id.hThread = (HANDLE)hThread;
516 ResumeThread((HANDLE)hThread);
519 i_ret = ( p_priv->thread_id.hThread ? 0 : 1 );
521 if( !i_ret && i_priority )
523 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
525 msg_Warn( p_this, "couldn't set a faster priority" );
530 #elif defined( HAVE_KERNEL_SCHEDULER_H )
531 p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
532 i_priority, p_data );
533 i_ret = resume_thread( p_priv->thread_id );
535 #elif defined( LIBVLC_USE_PTHREAD )
536 i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
539 if( config_GetInt( p_this, "rt-priority" ) )
542 int i_error, i_policy;
543 struct sched_param param;
545 memset( ¶m, 0, sizeof(struct sched_param) );
546 if( config_GetType( p_this, "rt-offset" ) )
548 i_priority += config_GetInt( p_this, "rt-offset" );
550 if( i_priority <= 0 )
552 param.sched_priority = (-1) * i_priority;
553 i_policy = SCHED_OTHER;
557 param.sched_priority = i_priority;
560 if( (i_error = pthread_setschedparam( p_priv->thread_id,
561 i_policy, ¶m )) )
564 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
582 msg_Dbg( p_this, "waiting for thread completion" );
583 vlc_object_wait( p_this );
586 p_priv->b_thread = true;
588 #if defined( WIN32 ) || defined( UNDER_CE )
589 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
590 (unsigned int)p_priv->thread_id.id, psz_name,
591 i_priority, psz_file, i_line );
593 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
594 (unsigned int)p_priv->thread_id, psz_name, i_priority,
599 vlc_mutex_unlock( &p_this->object_lock );
604 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
605 psz_name, psz_file, i_line );
606 vlc_mutex_unlock( &p_this->object_lock );
612 /*****************************************************************************
613 * vlc_thread_set_priority: set the priority of the current thread when we
614 * couldn't set it in vlc_thread_create (for instance for the main thread)
615 *****************************************************************************/
616 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
617 int i_line, int i_priority )
619 vlc_object_internals_t *p_priv = p_this->p_internals;
620 #if defined( WIN32 ) || defined( UNDER_CE )
621 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
623 if( !p_priv->thread_id.hThread )
624 p_priv->thread_id.hThread = GetCurrentThread();
625 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
627 msg_Warn( p_this, "couldn't set a faster priority" );
631 #elif defined( LIBVLC_USE_PTHREAD )
633 if( config_GetInt( p_this, "rt-priority" ) > 0 )
636 int i_error, i_policy;
637 struct sched_param param;
639 memset( ¶m, 0, sizeof(struct sched_param) );
640 if( config_GetType( p_this, "rt-offset" ) )
642 i_priority += config_GetInt( p_this, "rt-offset" );
644 if( i_priority <= 0 )
646 param.sched_priority = (-1) * i_priority;
647 i_policy = SCHED_OTHER;
651 param.sched_priority = i_priority;
654 if( !p_priv->thread_id )
655 p_priv->thread_id = pthread_self();
656 if( (i_error = pthread_setschedparam( p_priv->thread_id,
657 i_policy, ¶m )) )
660 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
670 /*****************************************************************************
671 * vlc_thread_ready: tell the parent thread we were successfully spawned
672 *****************************************************************************/
673 void __vlc_thread_ready( vlc_object_t *p_this )
675 vlc_object_signal( p_this );
678 /*****************************************************************************
679 * vlc_thread_join: wait until a thread exits, inner version
680 *****************************************************************************/
681 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
683 vlc_object_internals_t *p_priv = p_this->p_internals;
685 #if defined( UNDER_CE ) || defined( WIN32 )
687 BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
688 FILETIME*, FILETIME* );
689 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
690 int64_t real_time, kernel_time, user_time;
694 ** object will close its thread handle when destroyed, duplicate it here
695 ** to be on the safe side
697 if( ! DuplicateHandle(GetCurrentProcess(),
698 p_priv->thread_id.hThread,
703 DUPLICATE_SAME_ACCESS) )
705 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%u)",
706 (unsigned int)p_priv->thread_id.id,
707 psz_file, i_line, (unsigned int)GetLastError() );
708 p_priv->b_thread = false;
712 WaitForSingleObject( hThread, INFINITE );
714 msg_Dbg( p_this, "thread %u joined (%s:%d)",
715 (unsigned int)p_priv->thread_id.id,
717 #if defined( UNDER_CE )
718 hmodule = GetModuleHandle( _T("COREDLL") );
720 hmodule = GetModuleHandle( _T("KERNEL32") );
722 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
723 FILETIME*, FILETIME* ))
724 GetProcAddress( hmodule, _T("GetThreadTimes") );
726 if( OurGetThreadTimes &&
727 OurGetThreadTimes( hThread,
728 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
731 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
732 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
736 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
737 kernel_ft.dwLowDateTime) / 10;
740 ((((int64_t)user_ft.dwHighDateTime)<<32)|
741 user_ft.dwLowDateTime) / 10;
743 msg_Dbg( p_this, "thread times: "
744 "real "I64Fd"m%fs, kernel "I64Fd"m%fs, user "I64Fd"m%fs",
745 real_time/60/1000000,
746 (double)((real_time%(60*1000000))/1000000.0),
747 kernel_time/60/1000000,
748 (double)((kernel_time%(60*1000000))/1000000.0),
749 user_time/60/1000000,
750 (double)((user_time%(60*1000000))/1000000.0) );
752 CloseHandle( hThread );
754 #else /* !defined(WIN32) */
758 #if defined( HAVE_KERNEL_SCHEDULER_H )
760 i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
762 #elif defined( LIBVLC_USE_PTHREAD )
763 /* Make sure we do return if we are calling vlc_thread_join()
764 * from the joined thread */
765 if (pthread_equal (pthread_self (), p_priv->thread_id))
766 i_ret = pthread_detach (p_priv->thread_id);
768 i_ret = pthread_join (p_priv->thread_id, NULL);
774 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%m)",
775 (unsigned int)p_priv->thread_id, psz_file, i_line );
779 msg_Dbg( p_this, "thread %u joined (%s:%d)",
780 (unsigned int)p_priv->thread_id, psz_file, i_line );
785 p_priv->b_thread = false;