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.24 2002/11/10 18:04:24 sam 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( WIN32 )
43 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
44 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
45 #elif defined( HAVE_CTHREADS_H )
46 #elif defined( HAVE_KERNEL_SCHEDULER_H )
49 /*****************************************************************************
50 * Global variable for named mutexes
51 *****************************************************************************/
52 typedef struct vlc_namedmutex_t vlc_namedmutex_t;
53 struct vlc_namedmutex_t
59 vlc_namedmutex_t *p_next;
62 /*****************************************************************************
63 * vlc_threads_init: initialize threads system
64 *****************************************************************************
65 * This function requires lazy initialization of a global lock in order to
66 * keep the library really thread-safe. Some architectures don't support this
67 * and thus do not guarantee the complete reentrancy.
68 *****************************************************************************/
69 int __vlc_threads_init( vlc_object_t *p_this )
71 static volatile int i_status = VLC_THREADS_UNINITIALIZED;
73 libvlc_t *p_libvlc = (libvlc_t *)p_this;
74 int i_ret = VLC_SUCCESS;
76 /* If we have lazy mutex initialization, use it. Otherwise, we just
77 * hope nothing wrong happens. */
78 #if defined( PTH_INIT_IN_PTH_H )
79 #elif defined( ST_INIT_IN_ST_H )
80 #elif defined( WIN32 )
82 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
83 pthread_mutex_lock( &once_mutex );
84 #elif defined( HAVE_CTHREADS_H )
85 #elif defined( HAVE_KERNEL_SCHEDULER_H )
88 if( i_status == VLC_THREADS_UNINITIALIZED )
90 i_status = VLC_THREADS_PENDING;
92 /* We should be safe now. Do all the initialization stuff we want. */
93 vlc_object_create( p_libvlc, VLC_OBJECT_ROOT );
94 p_libvlc->b_ready = VLC_FALSE;
96 #if defined( PTH_INIT_IN_PTH_H )
99 #elif defined( ST_INIT_IN_ST_H )
102 #elif defined( UNDER_CE )
103 /* Nothing to initialize */
105 #elif defined( WIN32 )
106 /* Dynamically get the address of SignalObjectAndWait */
107 if( GetVersion() < 0x80000000 )
109 /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
110 hInstLib = LoadLibrary( "kernel32" );
113 p_libvlc->SignalObjectAndWait =
114 (SIGNALOBJECTANDWAIT)GetProcAddress( hInstLib,
115 "SignalObjectAndWait" );
120 p_libvlc->SignalObjectAndWait = NULL;
123 p_libvlc->b_fast_mutex = 0;
124 p_libvlc->i_win9x_cv = 0;
126 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
127 #elif defined( HAVE_CTHREADS_H )
128 #elif defined( HAVE_KERNEL_SCHEDULER_H )
133 i_status = VLC_THREADS_ERROR;
138 i_status = VLC_THREADS_READY;
143 /* Just increment the initialization count */
147 /* If we have lazy mutex initialization support, unlock the mutex;
148 * otherwize, do a naive wait loop. */
149 #if defined( PTH_INIT_IN_PTH_H )
150 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
151 #elif defined( ST_INIT_IN_ST_H )
152 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
153 #elif defined( WIN32 )
154 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
155 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
156 pthread_mutex_unlock( &once_mutex );
157 #elif defined( HAVE_CTHREADS_H )
158 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
159 #elif defined( HAVE_KERNEL_SCHEDULER_H )
160 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
163 if( i_status != VLC_THREADS_READY )
171 /*****************************************************************************
172 * vlc_threads_end: stop threads system
173 *****************************************************************************
174 * FIXME: This function is far from being threadsafe. We should undo exactly
175 * what we did above in vlc_threads_init.
176 *****************************************************************************/
177 int __vlc_threads_end( vlc_object_t *p_this )
179 #if defined( PTH_INIT_IN_PTH_H )
181 if( i_initializations == 0 )
186 #elif defined( ST_INIT_IN_ST_H )
189 #elif defined( WIN32 )
192 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
193 pthread_mutex_lock( &once_mutex );
195 pthread_mutex_unlock( &once_mutex );
197 #elif defined( HAVE_CTHREADS_H )
200 #elif defined( HAVE_KERNEL_SCHEDULER_H )
207 /*****************************************************************************
208 * Prototype for GPROF wrapper
209 *****************************************************************************/
211 /* Wrapper function for profiling */
212 static void * vlc_thread_wrapper ( void *p_wrapper );
216 # define ITIMER_REAL 1
217 # define ITIMER_PROF 2
221 struct timeval it_value;
222 struct timeval it_interval;
225 int setitimer(int kind, const struct itimerval* itnew, struct itimerval* itold);
228 typedef struct wrapper_t
230 /* Data lock access */
234 /* Data used to spawn the real thread */
235 vlc_thread_func_t func;
238 /* Profiling timer passed to the thread */
239 struct itimerval itimer;
245 /*****************************************************************************
246 * vlc_mutex_init: initialize a mutex
247 *****************************************************************************/
248 int __vlc_mutex_init( vlc_object_t *p_this, vlc_mutex_t *p_mutex )
250 p_mutex->p_this = p_this;
252 #if defined( PTH_INIT_IN_PTH_H )
253 return pth_mutex_init( &p_mutex->mutex );
255 #elif defined( ST_INIT_IN_ST_H )
256 p_mutex->mutex = st_mutex_new();
257 return ( p_mutex->mutex == NULL ) ? errno : 0;
259 #elif defined( WIN32 )
260 /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
261 * function and have a 100% correct vlc_cond_wait() implementation.
262 * As this function is not available on Win9x, we can use the faster
263 * CriticalSections */
264 # if !defined( UNDER_CE )
265 if( p_this->p_libvlc->SignalObjectAndWait &&
266 !p_this->p_libvlc->b_fast_mutex )
268 /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
269 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
270 return ( p_mutex->mutex != NULL ? 0 : 1 );
275 p_mutex->mutex = NULL;
276 InitializeCriticalSection( &p_mutex->csection );
280 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
281 # if defined(DEBUG) && defined(SYS_LINUX)
283 /* Create error-checking mutex to detect problems more easily. */
284 pthread_mutexattr_t attr;
287 pthread_mutexattr_init( &attr );
288 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
289 i_result = pthread_mutex_init( &p_mutex->mutex, &attr );
290 pthread_mutexattr_destroy( &attr );
294 return pthread_mutex_init( &p_mutex->mutex, NULL );
296 #elif defined( HAVE_CTHREADS_H )
297 mutex_init( p_mutex );
300 #elif defined( HAVE_KERNEL_SCHEDULER_H )
301 /* check the arguments and whether it's already been initialized */
302 if( p_mutex == NULL )
307 if( p_mutex->init == 9999 )
312 p_mutex->lock = create_sem( 1, "BeMutex" );
313 if( p_mutex->lock < B_NO_ERROR )
318 p_mutex->init = 9999;
324 /*****************************************************************************
325 * vlc_mutex_destroy: destroy a mutex, inner version
326 *****************************************************************************/
327 int __vlc_mutex_destroy( char * psz_file, int i_line, vlc_mutex_t *p_mutex )
330 /* In case of error : */
332 const char * psz_error = "";
334 #if defined( PTH_INIT_IN_PTH_H )
337 #elif defined( ST_INIT_IN_ST_H )
338 i_result = st_mutex_destroy( p_mutex->mutex );
340 #elif defined( WIN32 )
343 CloseHandle( p_mutex->mutex );
347 DeleteCriticalSection( &p_mutex->csection );
351 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
352 i_result = pthread_mutex_destroy( &p_mutex->mutex );
355 i_thread = (int)pthread_self();
356 psz_error = strerror(i_result);
359 #elif defined( HAVE_CTHREADS_H )
362 #elif defined( HAVE_KERNEL_SCHEDULER_H )
363 if( p_mutex->init == 9999 )
365 delete_sem( p_mutex->lock );
374 msg_Err( p_mutex->p_this,
375 "thread %d: mutex_destroy failed at %s:%d (%d:%s)",
376 i_thread, psz_file, i_line, i_result, psz_error );
381 /*****************************************************************************
382 * vlc_cond_init: initialize a condition
383 *****************************************************************************/
384 int __vlc_cond_init( vlc_object_t *p_this, vlc_cond_t *p_condvar )
386 p_condvar->p_this = p_this;
388 #if defined( PTH_INIT_IN_PTH_H )
389 return pth_cond_init( &p_condvar->cond );
391 #elif defined( ST_INIT_IN_ST_H )
392 p_condvar->cond = st_cond_new();
393 return ( p_condvar->cond == NULL ) ? errno : 0;
395 #elif defined( WIN32 )
396 /* Initialize counter */
397 p_condvar->i_waiting_threads = 0;
399 # if !defined( UNDER_CE )
401 p_condvar->i_win9x_cv = p_this->p_libvlc->i_win9x_cv;
402 p_condvar->SignalObjectAndWait = p_this->p_libvlc->SignalObjectAndWait;
404 if( (p_condvar->SignalObjectAndWait && !p_this->p_libvlc->b_fast_mutex)
405 || p_condvar->i_win9x_cv == 0 )
408 /* Create an auto-reset event. */
409 p_condvar->event = CreateEvent( NULL, /* no security */
410 FALSE, /* auto-reset event */
411 FALSE, /* start non-signaled */
412 NULL ); /* unnamed */
414 p_condvar->semaphore = NULL;
415 return !p_condvar->event;
416 # if !defined( UNDER_CE )
420 p_condvar->semaphore = CreateSemaphore( NULL, /* no security */
421 0, /* initial count */
422 0x7fffffff, /* max count */
423 NULL ); /* unnamed */
425 if( p_condvar->i_win9x_cv == 1 )
426 /* Create a manual-reset event initially signaled. */
427 p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
429 /* Create a auto-reset event. */
430 p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
432 InitializeCriticalSection( &p_condvar->csection );
434 return !p_condvar->semaphore || !p_condvar->event;
438 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
439 return pthread_cond_init( &p_condvar->cond, NULL );
441 #elif defined( HAVE_CTHREADS_H )
442 /* condition_init() */
443 spin_lock_init( &p_condvar->lock );
444 cthread_queue_init( &p_condvar->queue );
446 p_condvar->implications = 0;
450 #elif defined( HAVE_KERNEL_SCHEDULER_H )
456 if( p_condvar->init == 9999 )
461 p_condvar->thread = -1;
462 p_condvar->init = 9999;
467 /*****************************************************************************
468 * vlc_cond_destroy: destroy a condition, inner version
469 *****************************************************************************/
470 int __vlc_cond_destroy( char * psz_file, int i_line, vlc_cond_t *p_condvar )
473 /* In case of error : */
475 const char * psz_error = "";
477 #if defined( PTH_INIT_IN_PTH_H )
480 #elif defined( ST_INIT_IN_ST_H )
481 i_result = st_cond_destroy( p_condvar->cond );
483 #elif defined( WIN32 )
484 if( !p_condvar->semaphore )
485 i_result = !CloseHandle( p_condvar->event );
487 i_result = !CloseHandle( p_condvar->event )
488 || !CloseHandle( p_condvar->semaphore );
490 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
491 i_result = pthread_cond_destroy( &p_condvar->cond );
494 i_thread = (int)pthread_self();
495 psz_error = strerror(i_result);
498 #elif defined( HAVE_CTHREADS_H )
501 #elif defined( HAVE_KERNEL_SCHEDULER_H )
508 msg_Err( p_condvar->p_this,
509 "thread %d: cond_destroy failed at %s:%d (%d:%s)",
510 i_thread, psz_file, i_line, i_result, psz_error );
515 /*****************************************************************************
516 * vlc_thread_create: create a thread, inner version
517 *****************************************************************************
518 * Note that i_priority is only taken into account on platforms supporting
519 * userland real-time priority threads.
520 *****************************************************************************/
521 int __vlc_thread_create( vlc_object_t *p_this, char * psz_file, int i_line,
522 char *psz_name, void * ( *func ) ( void * ),
523 int i_priority, vlc_bool_t b_wait )
527 vlc_mutex_lock( &p_this->object_lock );
532 /* Initialize the wrapper structure */
534 wrapper.p_data = (void *)p_this;
535 getitimer( ITIMER_PROF, &wrapper.itimer );
536 vlc_mutex_init( p_this, &wrapper.lock );
537 vlc_cond_init( p_this, &wrapper.wait );
538 vlc_mutex_lock( &wrapper.lock );
540 /* Alter user-passed data so that we call the wrapper instead
541 * of the real function */
543 func = vlc_thread_wrapper;
546 #if defined( PTH_INIT_IN_PTH_H )
547 p_this->thread_id = pth_spawn( PTH_ATTR_DEFAULT, func, (void *)p_this );
550 #elif defined( ST_INIT_IN_ST_H )
551 p_this->thread_id = st_thread_create( func, (void *)p_this, 1, 0 );
554 #elif defined( WIN32 )
557 /* When using the MSVCRT C library you have to use the _beginthreadex
558 * function instead of CreateThread, otherwise you'll end up with
559 * memory leaks and the signal functions not working */
561 (HANDLE)_beginthreadex( NULL, 0, (PTHREAD_START) func,
562 (void *)p_this, 0, &threadID );
565 if ( p_this->thread_id && i_priority )
567 if ( !SetThreadPriority(p_this->thread_id, i_priority) )
569 msg_Warn( p_this, "couldn't set a faster priority" );
574 i_ret = ( p_this->thread_id ? 0 : 1 );
576 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
577 i_ret = pthread_create( &p_this->thread_id, NULL, func, (void *)p_this );
581 struct sched_param param;
582 memset( ¶m, 0, sizeof(struct sched_param) );
583 param.sched_priority = i_priority;
584 if ( pthread_setschedparam( p_this->thread_id, SCHED_RR, ¶m ) )
586 msg_Warn( p_this, "couldn't go to real-time priority" );
591 #elif defined( HAVE_CTHREADS_H )
592 p_this->thread_id = cthread_fork( (cthread_fn_t)func, (any_t)p_this );
595 #elif defined( HAVE_KERNEL_SCHEDULER_H )
596 p_this->thread_id = spawn_thread( (thread_func)func, psz_name,
597 B_NORMAL_PRIORITY, (void *)p_this );
598 i_ret = resume_thread( p_this->thread_id );
605 vlc_cond_wait( &wrapper.wait, &wrapper.lock );
608 vlc_mutex_unlock( &wrapper.lock );
609 vlc_mutex_destroy( &wrapper.lock );
610 vlc_cond_destroy( &wrapper.wait );
617 msg_Dbg( p_this, "waiting for thread completion" );
618 vlc_cond_wait( &p_this->object_wait, &p_this->object_lock );
621 p_this->b_thread = 1;
623 msg_Dbg( p_this, "thread %d (%s) created at priority %d (%s:%d)",
624 p_this->thread_id, psz_name, i_priority,
627 vlc_mutex_unlock( &p_this->object_lock );
631 msg_Err( p_this, "%s thread could not be created at %s:%d (%s)",
632 psz_name, psz_file, i_line, strerror(i_ret) );
633 vlc_mutex_unlock( &p_this->object_lock );
639 /*****************************************************************************
640 * vlc_thread_ready: tell the parent thread we were successfully spawned
641 *****************************************************************************/
642 void __vlc_thread_ready( vlc_object_t *p_this )
644 vlc_mutex_lock( &p_this->object_lock );
645 vlc_cond_signal( &p_this->object_wait );
646 vlc_mutex_unlock( &p_this->object_lock );
649 /*****************************************************************************
650 * vlc_thread_join: wait until a thread exits, inner version
651 *****************************************************************************/
652 void __vlc_thread_join( vlc_object_t *p_this, char * psz_file, int i_line )
656 #if defined( PTH_INIT_IN_PTH_H )
657 i_ret = pth_join( p_this->thread_id, NULL );
659 #elif defined( ST_INIT_IN_ST_H )
660 i_ret = st_thread_join( p_this->thread_id, NULL );
662 #elif defined( WIN32 )
663 WaitForSingleObject( p_this->thread_id, INFINITE );
665 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
666 i_ret = pthread_join( p_this->thread_id, NULL );
668 #elif defined( HAVE_CTHREADS_H )
669 cthread_join( p_this->thread_id );
672 #elif defined( HAVE_KERNEL_SCHEDULER_H )
674 wait_for_thread( p_this->thread_id, &exit_value );
680 msg_Err( p_this, "thread_join(%d) failed at %s:%d (%s)",
681 p_this->thread_id, psz_file, i_line, strerror(i_ret) );
685 msg_Dbg( p_this, "thread %d joined (%s:%d)",
686 p_this->thread_id, psz_file, i_line );
689 p_this->b_thread = 0;
692 /*****************************************************************************
693 * vlc_thread_wrapper: wrapper around thread functions used when profiling.
694 *****************************************************************************/
696 static void *vlc_thread_wrapper( void *p_wrapper )
698 /* Put user data in thread-local variables */
699 void * p_data = ((wrapper_t*)p_wrapper)->p_data;
700 vlc_thread_func_t func = ((wrapper_t*)p_wrapper)->func;
702 /* Set the profile timer value */
703 setitimer( ITIMER_PROF, &((wrapper_t*)p_wrapper)->itimer, NULL );
705 /* Tell the calling thread that we don't need its data anymore */
706 vlc_mutex_lock( &((wrapper_t*)p_wrapper)->lock );
707 vlc_cond_signal( &((wrapper_t*)p_wrapper)->wait );
708 vlc_mutex_unlock( &((wrapper_t*)p_wrapper)->lock );
710 /* Call the real function */
711 return func( p_data );