1 /*****************************************************************************
2 * threads.c : threads implementation for the VideoLAN client
3 *****************************************************************************
4 * Copyright (C) 1999, 2000, 2001, 2002 VideoLAN
5 * $Id: threads.c,v 1.38 2003/03/02 01:35:30 gbazin Exp $
7 * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
8 * Samuel Hocevar <sam@zoy.org>
9 * Gildas Bazin <gbazin@netcourrier.com>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
24 *****************************************************************************/
30 #define VLC_THREADS_UNINITIALIZED 0
31 #define VLC_THREADS_PENDING 1
32 #define VLC_THREADS_ERROR 2
33 #define VLC_THREADS_READY 3
35 /*****************************************************************************
36 * Global mutex for lazy initialization of the threads system
37 *****************************************************************************/
38 static volatile int i_initializations = 0;
40 #if defined( PTH_INIT_IN_PTH_H )
41 #elif defined( ST_INIT_IN_ST_H )
42 #elif defined( UNDER_CE )
43 #elif defined( WIN32 )
44 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
45 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
46 #elif defined( HAVE_CTHREADS_H )
47 #elif defined( HAVE_KERNEL_SCHEDULER_H )
50 /*****************************************************************************
51 * Global variable for named mutexes
52 *****************************************************************************/
53 typedef struct vlc_namedmutex_t vlc_namedmutex_t;
54 struct vlc_namedmutex_t
60 vlc_namedmutex_t *p_next;
63 /*****************************************************************************
64 * vlc_threads_init: initialize threads system
65 *****************************************************************************
66 * This function requires lazy initialization of a global lock in order to
67 * keep the library really thread-safe. Some architectures don't support this
68 * and thus do not guarantee the complete reentrancy.
69 *****************************************************************************/
70 int __vlc_threads_init( vlc_object_t *p_this )
72 static volatile int i_status = VLC_THREADS_UNINITIALIZED;
74 libvlc_t *p_libvlc = (libvlc_t *)p_this;
75 int i_ret = VLC_SUCCESS;
77 /* If we have lazy mutex initialization, use it. Otherwise, we just
78 * hope nothing wrong happens. */
79 #if defined( PTH_INIT_IN_PTH_H )
80 #elif defined( ST_INIT_IN_ST_H )
81 #elif defined( UNDER_CE )
82 #elif defined( WIN32 )
84 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
85 pthread_mutex_lock( &once_mutex );
86 #elif defined( HAVE_CTHREADS_H )
87 #elif defined( HAVE_KERNEL_SCHEDULER_H )
90 if( i_status == VLC_THREADS_UNINITIALIZED )
92 i_status = VLC_THREADS_PENDING;
94 /* We should be safe now. Do all the initialization stuff we want. */
95 p_libvlc->b_ready = VLC_FALSE;
97 #if defined( PTH_INIT_IN_PTH_H )
98 i_ret = ( pth_init() == FALSE );
100 #elif defined( ST_INIT_IN_ST_H )
103 #elif defined( UNDER_CE )
104 /* Nothing to initialize */
106 #elif defined( WIN32 )
107 /* Dynamically get the address of SignalObjectAndWait */
108 if( GetVersion() < 0x80000000 )
110 /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
111 hInstLib = LoadLibrary( "kernel32" );
114 p_libvlc->SignalObjectAndWait =
115 (SIGNALOBJECTANDWAIT)GetProcAddress( hInstLib,
116 "SignalObjectAndWait" );
121 p_libvlc->SignalObjectAndWait = NULL;
124 p_libvlc->b_fast_mutex = 0;
125 p_libvlc->i_win9x_cv = 0;
127 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
128 #elif defined( HAVE_CTHREADS_H )
129 #elif defined( HAVE_KERNEL_SCHEDULER_H )
132 vlc_object_create( p_libvlc, VLC_OBJECT_ROOT );
136 i_status = VLC_THREADS_ERROR;
141 i_status = VLC_THREADS_READY;
146 /* Just increment the initialization count */
150 /* If we have lazy mutex initialization support, unlock the mutex;
151 * otherwize, do a naive wait loop. */
152 #if defined( PTH_INIT_IN_PTH_H )
153 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
154 #elif defined( ST_INIT_IN_ST_H )
155 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
156 #elif defined( UNDER_CE )
157 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
158 #elif defined( WIN32 )
159 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
160 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
161 pthread_mutex_unlock( &once_mutex );
162 #elif defined( HAVE_CTHREADS_H )
163 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
164 #elif defined( HAVE_KERNEL_SCHEDULER_H )
165 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
168 if( i_status != VLC_THREADS_READY )
176 /*****************************************************************************
177 * vlc_threads_end: stop threads system
178 *****************************************************************************
179 * FIXME: This function is far from being threadsafe. We should undo exactly
180 * what we did above in vlc_threads_init.
181 *****************************************************************************/
182 int __vlc_threads_end( vlc_object_t *p_this )
184 #if defined( PTH_INIT_IN_PTH_H )
186 if( i_initializations == 0 )
188 return ( pth_kill() == FALSE );
191 #elif defined( ST_INIT_IN_ST_H )
194 #elif defined( UNDER_CE )
197 #elif defined( WIN32 )
200 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
201 pthread_mutex_lock( &once_mutex );
203 pthread_mutex_unlock( &once_mutex );
205 #elif defined( HAVE_CTHREADS_H )
208 #elif defined( HAVE_KERNEL_SCHEDULER_H )
215 /*****************************************************************************
216 * Prototype for GPROF wrapper
217 *****************************************************************************/
219 typedef void *(*vlc_thread_func_t)(void *p_data);
221 /* Wrapper function for profiling */
222 static void * vlc_thread_wrapper ( void *p_wrapper );
224 # if defined( WIN32 ) && !defined( UNDER_CE )
226 # define ITIMER_REAL 1
227 # define ITIMER_PROF 2
231 struct timeval it_value;
232 struct timeval it_interval;
235 int setitimer(int kind, const struct itimerval* itnew, struct itimerval* itold);
236 # endif /* WIN32 && !UNDER_CE */
238 typedef struct wrapper_t
240 /* Data lock access */
244 /* Data used to spawn the real thread */
245 vlc_thread_func_t func;
248 /* Profiling timer passed to the thread */
249 struct itimerval itimer;
255 /*****************************************************************************
256 * vlc_mutex_init: initialize a mutex
257 *****************************************************************************/
258 int __vlc_mutex_init( vlc_object_t *p_this, vlc_mutex_t *p_mutex )
260 p_mutex->p_this = p_this;
262 #if defined( PTH_INIT_IN_PTH_H )
263 return ( pth_mutex_init( &p_mutex->mutex ) == FALSE );
265 #elif defined( ST_INIT_IN_ST_H )
266 p_mutex->mutex = st_mutex_new();
267 return ( p_mutex->mutex == NULL ) ? errno : 0;
269 #elif defined( UNDER_CE )
270 InitializeCriticalSection( &p_mutex->csection );
273 #elif defined( WIN32 )
274 /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
275 * function and have a 100% correct vlc_cond_wait() implementation.
276 * As this function is not available on Win9x, we can use the faster
277 * CriticalSections */
278 if( p_this->p_libvlc->SignalObjectAndWait &&
279 !p_this->p_libvlc->b_fast_mutex )
281 /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
282 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
283 return ( p_mutex->mutex != NULL ? 0 : 1 );
287 p_mutex->mutex = NULL;
288 InitializeCriticalSection( &p_mutex->csection );
292 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
293 # if defined(DEBUG) && defined(SYS_LINUX)
295 /* Create error-checking mutex to detect problems more easily. */
296 pthread_mutexattr_t attr;
299 pthread_mutexattr_init( &attr );
300 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
301 i_result = pthread_mutex_init( &p_mutex->mutex, &attr );
302 pthread_mutexattr_destroy( &attr );
306 return pthread_mutex_init( &p_mutex->mutex, NULL );
308 #elif defined( HAVE_CTHREADS_H )
309 mutex_init( p_mutex );
312 #elif defined( HAVE_KERNEL_SCHEDULER_H )
313 /* check the arguments and whether it's already been initialized */
314 if( p_mutex == NULL )
319 if( p_mutex->init == 9999 )
324 p_mutex->lock = create_sem( 1, "BeMutex" );
325 if( p_mutex->lock < B_NO_ERROR )
330 p_mutex->init = 9999;
336 /*****************************************************************************
337 * vlc_mutex_destroy: destroy a mutex, inner version
338 *****************************************************************************/
339 int __vlc_mutex_destroy( char * psz_file, int i_line, vlc_mutex_t *p_mutex )
342 /* In case of error : */
344 const char * psz_error = "";
346 #if defined( PTH_INIT_IN_PTH_H )
349 #elif defined( ST_INIT_IN_ST_H )
350 i_result = st_mutex_destroy( p_mutex->mutex );
352 #elif defined( UNDER_CE )
353 DeleteCriticalSection( &p_mutex->csection );
356 #elif defined( WIN32 )
359 CloseHandle( p_mutex->mutex );
363 DeleteCriticalSection( &p_mutex->csection );
367 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
368 i_result = pthread_mutex_destroy( &p_mutex->mutex );
371 i_thread = (int)pthread_self();
372 psz_error = strerror(i_result);
375 #elif defined( HAVE_CTHREADS_H )
378 #elif defined( HAVE_KERNEL_SCHEDULER_H )
379 if( p_mutex->init == 9999 )
381 delete_sem( p_mutex->lock );
390 msg_Err( p_mutex->p_this,
391 "thread %d: mutex_destroy failed at %s:%d (%d:%s)",
392 i_thread, psz_file, i_line, i_result, psz_error );
397 /*****************************************************************************
398 * vlc_cond_init: initialize a condition
399 *****************************************************************************/
400 int __vlc_cond_init( vlc_object_t *p_this, vlc_cond_t *p_condvar )
402 p_condvar->p_this = p_this;
404 #if defined( PTH_INIT_IN_PTH_H )
405 return ( pth_cond_init( &p_condvar->cond ) == FALSE );
407 #elif defined( ST_INIT_IN_ST_H )
408 p_condvar->cond = st_cond_new();
409 return ( p_condvar->cond == NULL ) ? errno : 0;
411 #elif defined( UNDER_CE )
412 /* Initialize counter */
413 p_condvar->i_waiting_threads = 0;
415 /* Create an auto-reset event. */
416 p_condvar->event = CreateEvent( NULL, /* no security */
417 FALSE, /* auto-reset event */
418 FALSE, /* start non-signaled */
419 NULL ); /* unnamed */
420 return !p_condvar->event;
422 #elif defined( WIN32 )
423 /* Initialize counter */
424 p_condvar->i_waiting_threads = 0;
427 p_condvar->i_win9x_cv = p_this->p_libvlc->i_win9x_cv;
428 p_condvar->SignalObjectAndWait = p_this->p_libvlc->SignalObjectAndWait;
430 if( (p_condvar->SignalObjectAndWait && !p_this->p_libvlc->b_fast_mutex)
431 || p_condvar->i_win9x_cv == 0 )
433 /* Create an auto-reset event. */
434 p_condvar->event = CreateEvent( NULL, /* no security */
435 FALSE, /* auto-reset event */
436 FALSE, /* start non-signaled */
437 NULL ); /* unnamed */
439 p_condvar->semaphore = NULL;
440 return !p_condvar->event;
444 p_condvar->semaphore = CreateSemaphore( NULL, /* no security */
445 0, /* initial count */
446 0x7fffffff, /* max count */
447 NULL ); /* unnamed */
449 if( p_condvar->i_win9x_cv == 1 )
450 /* Create a manual-reset event initially signaled. */
451 p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
453 /* Create a auto-reset event. */
454 p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
456 InitializeCriticalSection( &p_condvar->csection );
458 return !p_condvar->semaphore || !p_condvar->event;
461 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
462 return pthread_cond_init( &p_condvar->cond, NULL );
464 #elif defined( HAVE_CTHREADS_H )
465 /* condition_init() */
466 spin_lock_init( &p_condvar->lock );
467 cthread_queue_init( &p_condvar->queue );
469 p_condvar->implications = 0;
473 #elif defined( HAVE_KERNEL_SCHEDULER_H )
479 if( p_condvar->init == 9999 )
484 p_condvar->thread = -1;
485 p_condvar->init = 9999;
490 /*****************************************************************************
491 * vlc_cond_destroy: destroy a condition, inner version
492 *****************************************************************************/
493 int __vlc_cond_destroy( char * psz_file, int i_line, vlc_cond_t *p_condvar )
496 /* In case of error : */
498 const char * psz_error = "";
500 #if defined( PTH_INIT_IN_PTH_H )
503 #elif defined( ST_INIT_IN_ST_H )
504 i_result = st_cond_destroy( p_condvar->cond );
506 #elif defined( UNDER_CE )
507 i_result = !CloseHandle( p_condvar->event );
509 #elif defined( WIN32 )
510 if( !p_condvar->semaphore )
511 i_result = !CloseHandle( p_condvar->event );
513 i_result = !CloseHandle( p_condvar->event )
514 || !CloseHandle( p_condvar->semaphore );
516 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
517 i_result = pthread_cond_destroy( &p_condvar->cond );
520 i_thread = (int)pthread_self();
521 psz_error = strerror(i_result);
524 #elif defined( HAVE_CTHREADS_H )
527 #elif defined( HAVE_KERNEL_SCHEDULER_H )
534 msg_Err( p_condvar->p_this,
535 "thread %d: cond_destroy failed at %s:%d (%d:%s)",
536 i_thread, psz_file, i_line, i_result, psz_error );
541 /*****************************************************************************
542 * vlc_thread_create: create a thread, inner version
543 *****************************************************************************
544 * Note that i_priority is only taken into account on platforms supporting
545 * userland real-time priority threads.
546 *****************************************************************************/
547 int __vlc_thread_create( vlc_object_t *p_this, char * psz_file, int i_line,
548 char *psz_name, void * ( *func ) ( void * ),
549 int i_priority, vlc_bool_t b_wait )
554 vlc_mutex_lock( &p_this->object_lock );
559 /* Initialize the wrapper structure */
561 wrapper.p_data = (void *)p_this;
562 getitimer( ITIMER_PROF, &wrapper.itimer );
563 vlc_mutex_init( p_this, &wrapper.lock );
564 vlc_cond_init( p_this, &wrapper.wait );
565 vlc_mutex_lock( &wrapper.lock );
567 /* Alter user-passed data so that we call the wrapper instead
568 * of the real function */
570 func = vlc_thread_wrapper;
572 p_data = (void *)p_this;
575 #if defined( PTH_INIT_IN_PTH_H )
576 p_this->thread_id = pth_spawn( PTH_ATTR_DEFAULT, func, p_data );
577 i_ret = p_this->thread_id == NULL;
579 #elif defined( ST_INIT_IN_ST_H )
580 p_this->thread_id = st_thread_create( func, p_data, 1, 0 );
583 #elif defined( WIN32 ) || defined( UNDER_CE )
586 /* When using the MSVCRT C library you have to use the _beginthreadex
587 * function instead of CreateThread, otherwise you'll end up with
588 * memory leaks and the signal functions not working (see Microsoft
589 * Knowledge Base, article 104641) */
591 #if defined( UNDER_CE )
592 (HANDLE)CreateThread( NULL, 0, (PTHREAD_START) func,
593 p_data, 0, &threadID );
595 (HANDLE)_beginthreadex( NULL, 0, (PTHREAD_START) func,
596 p_data, 0, &threadID );
600 if ( p_this->thread_id && i_priority )
602 if ( !SetThreadPriority(p_this->thread_id, i_priority) )
604 msg_Warn( p_this, "couldn't set a faster priority" );
609 i_ret = ( p_this->thread_id ? 0 : 1 );
611 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
612 i_ret = pthread_create( &p_this->thread_id, NULL, func, p_data );
617 struct sched_param param;
618 memset( ¶m, 0, sizeof(struct sched_param) );
619 param.sched_priority = i_priority;
620 if ( (i_error = pthread_setschedparam( p_this->thread_id,
621 SCHED_RR, ¶m )) )
623 msg_Warn( p_this, "couldn't go to real-time priority (%s:%d): %s",
624 psz_file, i_line, strerror(i_error) );
630 #elif defined( HAVE_CTHREADS_H )
631 p_this->thread_id = cthread_fork( (cthread_fn_t)func, (any_t)p_data );
634 #elif defined( HAVE_KERNEL_SCHEDULER_H )
635 p_this->thread_id = spawn_thread( (thread_func)func, psz_name,
636 i_priority, p_data );
637 i_ret = resume_thread( p_this->thread_id );
644 vlc_cond_wait( &wrapper.wait, &wrapper.lock );
647 vlc_mutex_unlock( &wrapper.lock );
648 vlc_mutex_destroy( &wrapper.lock );
649 vlc_cond_destroy( &wrapper.wait );
656 msg_Dbg( p_this, "waiting for thread completion" );
657 vlc_cond_wait( &p_this->object_wait, &p_this->object_lock );
660 p_this->b_thread = 1;
662 msg_Dbg( p_this, "thread %d (%s) created at priority %d (%s:%d)",
663 (int)p_this->thread_id, psz_name, i_priority,
666 vlc_mutex_unlock( &p_this->object_lock );
671 msg_Err( p_this, "%s thread could not be created at %s:%d (%s)",
672 psz_name, psz_file, i_line, strerror(i_ret) );
674 msg_Err( p_this, "%s thread could not be created at %s:%d",
675 psz_name, psz_file, i_line );
677 vlc_mutex_unlock( &p_this->object_lock );
683 /*****************************************************************************
684 * vlc_thread_set_priority: set the priority of the current thread when we
685 * couldn't set it in vlc_thread_create (for instance for the main thread)
686 *****************************************************************************/
687 int __vlc_thread_set_priority( vlc_object_t *p_this, char * psz_file,
688 int i_line, int i_priority )
690 #if defined( PTH_INIT_IN_PTH_H ) || defined( ST_INIT_IN_ST_H )
691 #elif defined( WIN32 ) || defined( UNDER_CE )
692 if ( !SetThreadPriority(GetCurrentThread(), i_priority) )
694 msg_Warn( p_this, "couldn't set a faster priority" );
698 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
702 struct sched_param param;
703 memset( ¶m, 0, sizeof(struct sched_param) );
704 param.sched_priority = i_priority;
705 if ( (i_error = pthread_setschedparam( pthread_self(),
706 SCHED_RR, ¶m )) )
708 msg_Warn( p_this, "couldn't go to real-time priority (%s:%d): %s",
709 psz_file, i_line, strerror(i_error) );
719 /*****************************************************************************
720 * vlc_thread_ready: tell the parent thread we were successfully spawned
721 *****************************************************************************/
722 void __vlc_thread_ready( vlc_object_t *p_this )
724 vlc_mutex_lock( &p_this->object_lock );
725 vlc_cond_signal( &p_this->object_wait );
726 vlc_mutex_unlock( &p_this->object_lock );
729 /*****************************************************************************
730 * vlc_thread_join: wait until a thread exits, inner version
731 *****************************************************************************/
732 void __vlc_thread_join( vlc_object_t *p_this, char * psz_file, int i_line )
736 #if defined( PTH_INIT_IN_PTH_H )
737 i_ret = ( pth_join( p_this->thread_id, NULL ) == FALSE );
739 #elif defined( ST_INIT_IN_ST_H )
740 i_ret = st_thread_join( p_this->thread_id, NULL );
742 #elif defined( UNDER_CE )
743 WaitForSingleObject( p_this->thread_id, INFINITE );
745 #elif defined( WIN32 )
746 WaitForSingleObject( p_this->thread_id, INFINITE );
748 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
749 i_ret = pthread_join( p_this->thread_id, NULL );
751 #elif defined( HAVE_CTHREADS_H )
752 cthread_join( p_this->thread_id );
755 #elif defined( HAVE_KERNEL_SCHEDULER_H )
757 wait_for_thread( p_this->thread_id, &exit_value );
764 msg_Err( p_this, "thread_join(%d) failed at %s:%d (%s)",
765 (int)p_this->thread_id, psz_file, i_line,
768 msg_Err( p_this, "thread_join(%d) failed at %s:%d",
769 (int)p_this->thread_id, psz_file, i_line );
774 msg_Dbg( p_this, "thread %d joined (%s:%d)",
775 (int)p_this->thread_id, psz_file, i_line );
778 p_this->b_thread = 0;
781 /*****************************************************************************
782 * vlc_thread_wrapper: wrapper around thread functions used when profiling.
783 *****************************************************************************/
785 static void *vlc_thread_wrapper( void *p_wrapper )
787 /* Put user data in thread-local variables */
788 void * p_data = ((wrapper_t*)p_wrapper)->p_data;
789 vlc_thread_func_t func = ((wrapper_t*)p_wrapper)->func;
791 /* Set the profile timer value */
792 setitimer( ITIMER_PROF, &((wrapper_t*)p_wrapper)->itimer, NULL );
794 /* Tell the calling thread that we don't need its data anymore */
795 vlc_mutex_lock( &((wrapper_t*)p_wrapper)->lock );
796 vlc_cond_signal( &((wrapper_t*)p_wrapper)->wait );
797 vlc_mutex_unlock( &((wrapper_t*)p_wrapper)->lock );
799 /* Call the real function */
800 return func( p_data );