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.25 2002/11/10 23:41:53 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( UNDER_CE )
81 #elif defined( WIN32 )
83 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
84 pthread_mutex_lock( &once_mutex );
85 #elif defined( HAVE_CTHREADS_H )
86 #elif defined( HAVE_KERNEL_SCHEDULER_H )
89 if( i_status == VLC_THREADS_UNINITIALIZED )
91 i_status = VLC_THREADS_PENDING;
93 /* We should be safe now. Do all the initialization stuff we want. */
94 vlc_object_create( p_libvlc, VLC_OBJECT_ROOT );
95 p_libvlc->b_ready = VLC_FALSE;
97 #if defined( PTH_INIT_IN_PTH_H )
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 )
134 i_status = VLC_THREADS_ERROR;
139 i_status = VLC_THREADS_READY;
144 /* Just increment the initialization count */
148 /* If we have lazy mutex initialization support, unlock the mutex;
149 * otherwize, do a naive wait loop. */
150 #if defined( PTH_INIT_IN_PTH_H )
151 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
152 #elif defined( ST_INIT_IN_ST_H )
153 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
154 #elif defined( WIN32 )
155 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
156 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
157 pthread_mutex_unlock( &once_mutex );
158 #elif defined( HAVE_CTHREADS_H )
159 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
160 #elif defined( HAVE_KERNEL_SCHEDULER_H )
161 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
164 if( i_status != VLC_THREADS_READY )
172 /*****************************************************************************
173 * vlc_threads_end: stop threads system
174 *****************************************************************************
175 * FIXME: This function is far from being threadsafe. We should undo exactly
176 * what we did above in vlc_threads_init.
177 *****************************************************************************/
178 int __vlc_threads_end( vlc_object_t *p_this )
180 #if defined( PTH_INIT_IN_PTH_H )
182 if( i_initializations == 0 )
187 #elif defined( ST_INIT_IN_ST_H )
190 #elif defined( WIN32 )
193 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
194 pthread_mutex_lock( &once_mutex );
196 pthread_mutex_unlock( &once_mutex );
198 #elif defined( HAVE_CTHREADS_H )
201 #elif defined( HAVE_KERNEL_SCHEDULER_H )
208 /*****************************************************************************
209 * Prototype for GPROF wrapper
210 *****************************************************************************/
212 /* Wrapper function for profiling */
213 static void * vlc_thread_wrapper ( void *p_wrapper );
217 # define ITIMER_REAL 1
218 # define ITIMER_PROF 2
222 struct timeval it_value;
223 struct timeval it_interval;
226 int setitimer(int kind, const struct itimerval* itnew, struct itimerval* itold);
229 typedef struct wrapper_t
231 /* Data lock access */
235 /* Data used to spawn the real thread */
236 vlc_thread_func_t func;
239 /* Profiling timer passed to the thread */
240 struct itimerval itimer;
246 /*****************************************************************************
247 * vlc_mutex_init: initialize a mutex
248 *****************************************************************************/
249 int __vlc_mutex_init( vlc_object_t *p_this, vlc_mutex_t *p_mutex )
251 p_mutex->p_this = p_this;
253 #if defined( PTH_INIT_IN_PTH_H )
254 return pth_mutex_init( &p_mutex->mutex );
256 #elif defined( ST_INIT_IN_ST_H )
257 p_mutex->mutex = st_mutex_new();
258 return ( p_mutex->mutex == NULL ) ? errno : 0;
260 #elif defined( WIN32 )
261 /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
262 * function and have a 100% correct vlc_cond_wait() implementation.
263 * As this function is not available on Win9x, we can use the faster
264 * CriticalSections */
265 # if !defined( UNDER_CE )
266 if( p_this->p_libvlc->SignalObjectAndWait &&
267 !p_this->p_libvlc->b_fast_mutex )
269 /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
270 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
271 return ( p_mutex->mutex != NULL ? 0 : 1 );
276 p_mutex->mutex = NULL;
277 InitializeCriticalSection( &p_mutex->csection );
281 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
282 # if defined(DEBUG) && defined(SYS_LINUX)
284 /* Create error-checking mutex to detect problems more easily. */
285 pthread_mutexattr_t attr;
288 pthread_mutexattr_init( &attr );
289 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
290 i_result = pthread_mutex_init( &p_mutex->mutex, &attr );
291 pthread_mutexattr_destroy( &attr );
295 return pthread_mutex_init( &p_mutex->mutex, NULL );
297 #elif defined( HAVE_CTHREADS_H )
298 mutex_init( p_mutex );
301 #elif defined( HAVE_KERNEL_SCHEDULER_H )
302 /* check the arguments and whether it's already been initialized */
303 if( p_mutex == NULL )
308 if( p_mutex->init == 9999 )
313 p_mutex->lock = create_sem( 1, "BeMutex" );
314 if( p_mutex->lock < B_NO_ERROR )
319 p_mutex->init = 9999;
325 /*****************************************************************************
326 * vlc_mutex_destroy: destroy a mutex, inner version
327 *****************************************************************************/
328 int __vlc_mutex_destroy( char * psz_file, int i_line, vlc_mutex_t *p_mutex )
331 /* In case of error : */
333 const char * psz_error = "";
335 #if defined( PTH_INIT_IN_PTH_H )
338 #elif defined( ST_INIT_IN_ST_H )
339 i_result = st_mutex_destroy( p_mutex->mutex );
341 #elif defined( WIN32 )
344 CloseHandle( p_mutex->mutex );
348 DeleteCriticalSection( &p_mutex->csection );
352 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
353 i_result = pthread_mutex_destroy( &p_mutex->mutex );
356 i_thread = (int)pthread_self();
357 psz_error = strerror(i_result);
360 #elif defined( HAVE_CTHREADS_H )
363 #elif defined( HAVE_KERNEL_SCHEDULER_H )
364 if( p_mutex->init == 9999 )
366 delete_sem( p_mutex->lock );
375 msg_Err( p_mutex->p_this,
376 "thread %d: mutex_destroy failed at %s:%d (%d:%s)",
377 i_thread, psz_file, i_line, i_result, psz_error );
382 /*****************************************************************************
383 * vlc_cond_init: initialize a condition
384 *****************************************************************************/
385 int __vlc_cond_init( vlc_object_t *p_this, vlc_cond_t *p_condvar )
387 p_condvar->p_this = p_this;
389 #if defined( PTH_INIT_IN_PTH_H )
390 return pth_cond_init( &p_condvar->cond );
392 #elif defined( ST_INIT_IN_ST_H )
393 p_condvar->cond = st_cond_new();
394 return ( p_condvar->cond == NULL ) ? errno : 0;
396 #elif defined( WIN32 )
397 /* Initialize counter */
398 p_condvar->i_waiting_threads = 0;
400 # if !defined( UNDER_CE )
402 p_condvar->i_win9x_cv = p_this->p_libvlc->i_win9x_cv;
403 p_condvar->SignalObjectAndWait = p_this->p_libvlc->SignalObjectAndWait;
405 if( (p_condvar->SignalObjectAndWait && !p_this->p_libvlc->b_fast_mutex)
406 || p_condvar->i_win9x_cv == 0 )
409 /* Create an auto-reset event. */
410 p_condvar->event = CreateEvent( NULL, /* no security */
411 FALSE, /* auto-reset event */
412 FALSE, /* start non-signaled */
413 NULL ); /* unnamed */
415 p_condvar->semaphore = NULL;
416 return !p_condvar->event;
417 # if !defined( UNDER_CE )
421 p_condvar->semaphore = CreateSemaphore( NULL, /* no security */
422 0, /* initial count */
423 0x7fffffff, /* max count */
424 NULL ); /* unnamed */
426 if( p_condvar->i_win9x_cv == 1 )
427 /* Create a manual-reset event initially signaled. */
428 p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
430 /* Create a auto-reset event. */
431 p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
433 InitializeCriticalSection( &p_condvar->csection );
435 return !p_condvar->semaphore || !p_condvar->event;
439 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
440 return pthread_cond_init( &p_condvar->cond, NULL );
442 #elif defined( HAVE_CTHREADS_H )
443 /* condition_init() */
444 spin_lock_init( &p_condvar->lock );
445 cthread_queue_init( &p_condvar->queue );
447 p_condvar->implications = 0;
451 #elif defined( HAVE_KERNEL_SCHEDULER_H )
457 if( p_condvar->init == 9999 )
462 p_condvar->thread = -1;
463 p_condvar->init = 9999;
468 /*****************************************************************************
469 * vlc_cond_destroy: destroy a condition, inner version
470 *****************************************************************************/
471 int __vlc_cond_destroy( char * psz_file, int i_line, vlc_cond_t *p_condvar )
474 /* In case of error : */
476 const char * psz_error = "";
478 #if defined( PTH_INIT_IN_PTH_H )
481 #elif defined( ST_INIT_IN_ST_H )
482 i_result = st_cond_destroy( p_condvar->cond );
484 #elif defined( WIN32 )
485 if( !p_condvar->semaphore )
486 i_result = !CloseHandle( p_condvar->event );
488 i_result = !CloseHandle( p_condvar->event )
489 || !CloseHandle( p_condvar->semaphore );
491 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
492 i_result = pthread_cond_destroy( &p_condvar->cond );
495 i_thread = (int)pthread_self();
496 psz_error = strerror(i_result);
499 #elif defined( HAVE_CTHREADS_H )
502 #elif defined( HAVE_KERNEL_SCHEDULER_H )
509 msg_Err( p_condvar->p_this,
510 "thread %d: cond_destroy failed at %s:%d (%d:%s)",
511 i_thread, psz_file, i_line, i_result, psz_error );
516 /*****************************************************************************
517 * vlc_thread_create: create a thread, inner version
518 *****************************************************************************
519 * Note that i_priority is only taken into account on platforms supporting
520 * userland real-time priority threads.
521 *****************************************************************************/
522 int __vlc_thread_create( vlc_object_t *p_this, char * psz_file, int i_line,
523 char *psz_name, void * ( *func ) ( void * ),
524 int i_priority, vlc_bool_t b_wait )
528 vlc_mutex_lock( &p_this->object_lock );
533 /* Initialize the wrapper structure */
535 wrapper.p_data = (void *)p_this;
536 getitimer( ITIMER_PROF, &wrapper.itimer );
537 vlc_mutex_init( p_this, &wrapper.lock );
538 vlc_cond_init( p_this, &wrapper.wait );
539 vlc_mutex_lock( &wrapper.lock );
541 /* Alter user-passed data so that we call the wrapper instead
542 * of the real function */
544 func = vlc_thread_wrapper;
547 #if defined( PTH_INIT_IN_PTH_H )
548 p_this->thread_id = pth_spawn( PTH_ATTR_DEFAULT, func, (void *)p_this );
551 #elif defined( ST_INIT_IN_ST_H )
552 p_this->thread_id = st_thread_create( func, (void *)p_this, 1, 0 );
555 #elif defined( WIN32 )
558 /* When using the MSVCRT C library you have to use the _beginthreadex
559 * function instead of CreateThread, otherwise you'll end up with
560 * memory leaks and the signal functions not working (see Microsoft
561 * Knowledge Base, article 104641) */
563 #if defined( UNDER_CE )
564 (HANDLE)CreateThread( NULL, 0, (PTHREAD_START) func,
565 (void *)p_this, 0, &threadID );
567 (HANDLE)_beginthreadex( NULL, 0, (PTHREAD_START) func,
568 (void *)p_this, 0, &threadID );
572 if ( p_this->thread_id && i_priority )
574 if ( !SetThreadPriority(p_this->thread_id, i_priority) )
576 msg_Warn( p_this, "couldn't set a faster priority" );
581 i_ret = ( p_this->thread_id ? 0 : 1 );
583 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
584 i_ret = pthread_create( &p_this->thread_id, NULL, func, (void *)p_this );
588 struct sched_param param;
589 memset( ¶m, 0, sizeof(struct sched_param) );
590 param.sched_priority = i_priority;
591 if ( pthread_setschedparam( p_this->thread_id, SCHED_RR, ¶m ) )
593 msg_Warn( p_this, "couldn't go to real-time priority" );
598 #elif defined( HAVE_CTHREADS_H )
599 p_this->thread_id = cthread_fork( (cthread_fn_t)func, (any_t)p_this );
602 #elif defined( HAVE_KERNEL_SCHEDULER_H )
603 p_this->thread_id = spawn_thread( (thread_func)func, psz_name,
604 B_NORMAL_PRIORITY, (void *)p_this );
605 i_ret = resume_thread( p_this->thread_id );
612 vlc_cond_wait( &wrapper.wait, &wrapper.lock );
615 vlc_mutex_unlock( &wrapper.lock );
616 vlc_mutex_destroy( &wrapper.lock );
617 vlc_cond_destroy( &wrapper.wait );
624 msg_Dbg( p_this, "waiting for thread completion" );
625 vlc_cond_wait( &p_this->object_wait, &p_this->object_lock );
628 p_this->b_thread = 1;
630 msg_Dbg( p_this, "thread %d (%s) created at priority %d (%s:%d)",
631 p_this->thread_id, psz_name, i_priority,
634 vlc_mutex_unlock( &p_this->object_lock );
639 msg_Err( p_this, "%s thread could not be created at %s:%d (%s)",
640 psz_name, psz_file, i_line, strerror(i_ret) );
642 msg_Err( p_this, "%s thread could not be created at %s:%d",
643 psz_name, psz_file, i_line );
645 vlc_mutex_unlock( &p_this->object_lock );
651 /*****************************************************************************
652 * vlc_thread_ready: tell the parent thread we were successfully spawned
653 *****************************************************************************/
654 void __vlc_thread_ready( vlc_object_t *p_this )
656 vlc_mutex_lock( &p_this->object_lock );
657 vlc_cond_signal( &p_this->object_wait );
658 vlc_mutex_unlock( &p_this->object_lock );
661 /*****************************************************************************
662 * vlc_thread_join: wait until a thread exits, inner version
663 *****************************************************************************/
664 void __vlc_thread_join( vlc_object_t *p_this, char * psz_file, int i_line )
668 #if defined( PTH_INIT_IN_PTH_H )
669 i_ret = pth_join( p_this->thread_id, NULL );
671 #elif defined( ST_INIT_IN_ST_H )
672 i_ret = st_thread_join( p_this->thread_id, NULL );
674 #elif defined( WIN32 )
675 WaitForSingleObject( p_this->thread_id, INFINITE );
677 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
678 i_ret = pthread_join( p_this->thread_id, NULL );
680 #elif defined( HAVE_CTHREADS_H )
681 cthread_join( p_this->thread_id );
684 #elif defined( HAVE_KERNEL_SCHEDULER_H )
686 wait_for_thread( p_this->thread_id, &exit_value );
693 msg_Err( p_this, "thread_join(%d) failed at %s:%d (%s)",
694 p_this->thread_id, psz_file, i_line, strerror(i_ret) );
696 msg_Err( p_this, "thread_join(%d) failed at %s:%d",
697 p_this->thread_id, psz_file, i_line );
702 msg_Dbg( p_this, "thread %d joined (%s:%d)",
703 p_this->thread_id, psz_file, i_line );
706 p_this->b_thread = 0;
709 /*****************************************************************************
710 * vlc_thread_wrapper: wrapper around thread functions used when profiling.
711 *****************************************************************************/
713 static void *vlc_thread_wrapper( void *p_wrapper )
715 /* Put user data in thread-local variables */
716 void * p_data = ((wrapper_t*)p_wrapper)->p_data;
717 vlc_thread_func_t func = ((wrapper_t*)p_wrapper)->func;
719 /* Set the profile timer value */
720 setitimer( ITIMER_PROF, &((wrapper_t*)p_wrapper)->itimer, NULL );
722 /* Tell the calling thread that we don't need its data anymore */
723 vlc_mutex_lock( &((wrapper_t*)p_wrapper)->lock );
724 vlc_cond_signal( &((wrapper_t*)p_wrapper)->wait );
725 vlc_mutex_unlock( &((wrapper_t*)p_wrapper)->lock );
727 /* Call the real function */
728 return func( p_data );