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.30 2002/12/18 14:17:11 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( 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 vlc_object_create( p_libvlc, VLC_OBJECT_ROOT );
96 p_libvlc->b_ready = VLC_FALSE;
98 #if defined( PTH_INIT_IN_PTH_H )
101 #elif defined( ST_INIT_IN_ST_H )
104 #elif defined( UNDER_CE )
105 /* Nothing to initialize */
107 #elif defined( WIN32 )
108 /* Dynamically get the address of SignalObjectAndWait */
109 if( GetVersion() < 0x80000000 )
111 /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
112 hInstLib = LoadLibrary( "kernel32" );
115 p_libvlc->SignalObjectAndWait =
116 (SIGNALOBJECTANDWAIT)GetProcAddress( hInstLib,
117 "SignalObjectAndWait" );
122 p_libvlc->SignalObjectAndWait = NULL;
125 p_libvlc->b_fast_mutex = 0;
126 p_libvlc->i_win9x_cv = 0;
128 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
129 #elif defined( HAVE_CTHREADS_H )
130 #elif defined( HAVE_KERNEL_SCHEDULER_H )
135 i_status = VLC_THREADS_ERROR;
140 i_status = VLC_THREADS_READY;
145 /* Just increment the initialization count */
149 /* If we have lazy mutex initialization support, unlock the mutex;
150 * otherwize, do a naive wait loop. */
151 #if defined( PTH_INIT_IN_PTH_H )
152 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
153 #elif defined( ST_INIT_IN_ST_H )
154 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
155 #elif defined( UNDER_CE )
156 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
157 #elif defined( WIN32 )
158 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
159 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
160 pthread_mutex_unlock( &once_mutex );
161 #elif defined( HAVE_CTHREADS_H )
162 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
163 #elif defined( HAVE_KERNEL_SCHEDULER_H )
164 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
167 if( i_status != VLC_THREADS_READY )
175 /*****************************************************************************
176 * vlc_threads_end: stop threads system
177 *****************************************************************************
178 * FIXME: This function is far from being threadsafe. We should undo exactly
179 * what we did above in vlc_threads_init.
180 *****************************************************************************/
181 int __vlc_threads_end( vlc_object_t *p_this )
183 #if defined( PTH_INIT_IN_PTH_H )
185 if( i_initializations == 0 )
190 #elif defined( ST_INIT_IN_ST_H )
193 #elif defined( UNDER_CE )
196 #elif defined( WIN32 )
199 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
200 pthread_mutex_lock( &once_mutex );
202 pthread_mutex_unlock( &once_mutex );
204 #elif defined( HAVE_CTHREADS_H )
207 #elif defined( HAVE_KERNEL_SCHEDULER_H )
214 /*****************************************************************************
215 * Prototype for GPROF wrapper
216 *****************************************************************************/
218 /* Wrapper function for profiling */
219 static void * vlc_thread_wrapper ( void *p_wrapper );
221 # if defined( WIN32 ) && !defined( UNDER_CE )
223 # define ITIMER_REAL 1
224 # define ITIMER_PROF 2
228 struct timeval it_value;
229 struct timeval it_interval;
232 int setitimer(int kind, const struct itimerval* itnew, struct itimerval* itold);
233 # endif /* WIN32 && !UNDER_CE */
235 typedef struct wrapper_t
237 /* Data lock access */
241 /* Data used to spawn the real thread */
242 vlc_thread_func_t func;
245 /* Profiling timer passed to the thread */
246 struct itimerval itimer;
252 /*****************************************************************************
253 * vlc_mutex_init: initialize a mutex
254 *****************************************************************************/
255 int __vlc_mutex_init( vlc_object_t *p_this, vlc_mutex_t *p_mutex )
257 p_mutex->p_this = p_this;
259 #if defined( PTH_INIT_IN_PTH_H )
260 return pth_mutex_init( &p_mutex->mutex );
262 #elif defined( ST_INIT_IN_ST_H )
263 p_mutex->mutex = st_mutex_new();
264 return ( p_mutex->mutex == NULL ) ? errno : 0;
266 #elif defined( UNDER_CE )
267 InitializeCriticalSection( &p_mutex->csection );
270 #elif defined( WIN32 )
271 /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
272 * function and have a 100% correct vlc_cond_wait() implementation.
273 * As this function is not available on Win9x, we can use the faster
274 * CriticalSections */
275 if( p_this->p_libvlc->SignalObjectAndWait &&
276 !p_this->p_libvlc->b_fast_mutex )
278 /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
279 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
280 return ( p_mutex->mutex != NULL ? 0 : 1 );
284 p_mutex->mutex = NULL;
285 InitializeCriticalSection( &p_mutex->csection );
289 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
290 # if defined(DEBUG) && defined(SYS_LINUX)
292 /* Create error-checking mutex to detect problems more easily. */
293 pthread_mutexattr_t attr;
296 pthread_mutexattr_init( &attr );
297 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
298 i_result = pthread_mutex_init( &p_mutex->mutex, &attr );
299 pthread_mutexattr_destroy( &attr );
303 return pthread_mutex_init( &p_mutex->mutex, NULL );
305 #elif defined( HAVE_CTHREADS_H )
306 mutex_init( p_mutex );
309 #elif defined( HAVE_KERNEL_SCHEDULER_H )
310 /* check the arguments and whether it's already been initialized */
311 if( p_mutex == NULL )
316 if( p_mutex->init == 9999 )
321 p_mutex->lock = create_sem( 1, "BeMutex" );
322 if( p_mutex->lock < B_NO_ERROR )
327 p_mutex->init = 9999;
333 /*****************************************************************************
334 * vlc_mutex_destroy: destroy a mutex, inner version
335 *****************************************************************************/
336 int __vlc_mutex_destroy( char * psz_file, int i_line, vlc_mutex_t *p_mutex )
339 /* In case of error : */
341 const char * psz_error = "";
343 #if defined( PTH_INIT_IN_PTH_H )
346 #elif defined( ST_INIT_IN_ST_H )
347 i_result = st_mutex_destroy( p_mutex->mutex );
349 #elif defined( UNDER_CE )
350 DeleteCriticalSection( &p_mutex->csection );
353 #elif defined( WIN32 )
356 CloseHandle( p_mutex->mutex );
360 DeleteCriticalSection( &p_mutex->csection );
364 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
365 i_result = pthread_mutex_destroy( &p_mutex->mutex );
368 i_thread = (int)pthread_self();
369 psz_error = strerror(i_result);
372 #elif defined( HAVE_CTHREADS_H )
375 #elif defined( HAVE_KERNEL_SCHEDULER_H )
376 if( p_mutex->init == 9999 )
378 delete_sem( p_mutex->lock );
387 msg_Err( p_mutex->p_this,
388 "thread %d: mutex_destroy failed at %s:%d (%d:%s)",
389 i_thread, psz_file, i_line, i_result, psz_error );
394 /*****************************************************************************
395 * vlc_cond_init: initialize a condition
396 *****************************************************************************/
397 int __vlc_cond_init( vlc_object_t *p_this, vlc_cond_t *p_condvar )
399 p_condvar->p_this = p_this;
401 #if defined( PTH_INIT_IN_PTH_H )
402 return pth_cond_init( &p_condvar->cond );
404 #elif defined( ST_INIT_IN_ST_H )
405 p_condvar->cond = st_cond_new();
406 return ( p_condvar->cond == NULL ) ? errno : 0;
408 #elif defined( UNDER_CE )
409 /* Initialize counter */
410 p_condvar->i_waiting_threads = 0;
412 /* Create an auto-reset event. */
413 p_condvar->event = CreateEvent( NULL, /* no security */
414 FALSE, /* auto-reset event */
415 FALSE, /* start non-signaled */
416 NULL ); /* unnamed */
417 return !p_condvar->event;
419 #elif defined( WIN32 )
420 /* Initialize counter */
421 p_condvar->i_waiting_threads = 0;
424 p_condvar->i_win9x_cv = p_this->p_libvlc->i_win9x_cv;
425 p_condvar->SignalObjectAndWait = p_this->p_libvlc->SignalObjectAndWait;
427 if( (p_condvar->SignalObjectAndWait && !p_this->p_libvlc->b_fast_mutex)
428 || p_condvar->i_win9x_cv == 0 )
430 /* Create an auto-reset event. */
431 p_condvar->event = CreateEvent( NULL, /* no security */
432 FALSE, /* auto-reset event */
433 FALSE, /* start non-signaled */
434 NULL ); /* unnamed */
436 p_condvar->semaphore = NULL;
437 return !p_condvar->event;
441 p_condvar->semaphore = CreateSemaphore( NULL, /* no security */
442 0, /* initial count */
443 0x7fffffff, /* max count */
444 NULL ); /* unnamed */
446 if( p_condvar->i_win9x_cv == 1 )
447 /* Create a manual-reset event initially signaled. */
448 p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
450 /* Create a auto-reset event. */
451 p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
453 InitializeCriticalSection( &p_condvar->csection );
455 return !p_condvar->semaphore || !p_condvar->event;
458 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
459 return pthread_cond_init( &p_condvar->cond, NULL );
461 #elif defined( HAVE_CTHREADS_H )
462 /* condition_init() */
463 spin_lock_init( &p_condvar->lock );
464 cthread_queue_init( &p_condvar->queue );
466 p_condvar->implications = 0;
470 #elif defined( HAVE_KERNEL_SCHEDULER_H )
476 if( p_condvar->init == 9999 )
481 p_condvar->thread = -1;
482 p_condvar->init = 9999;
487 /*****************************************************************************
488 * vlc_cond_destroy: destroy a condition, inner version
489 *****************************************************************************/
490 int __vlc_cond_destroy( char * psz_file, int i_line, vlc_cond_t *p_condvar )
493 /* In case of error : */
495 const char * psz_error = "";
497 #if defined( PTH_INIT_IN_PTH_H )
500 #elif defined( ST_INIT_IN_ST_H )
501 i_result = st_cond_destroy( p_condvar->cond );
503 #elif defined( UNDER_CE )
504 i_result = !CloseHandle( p_condvar->event );
506 #elif defined( WIN32 )
507 if( !p_condvar->semaphore )
508 i_result = !CloseHandle( p_condvar->event );
510 i_result = !CloseHandle( p_condvar->event )
511 || !CloseHandle( p_condvar->semaphore );
513 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
514 i_result = pthread_cond_destroy( &p_condvar->cond );
517 i_thread = (int)pthread_self();
518 psz_error = strerror(i_result);
521 #elif defined( HAVE_CTHREADS_H )
524 #elif defined( HAVE_KERNEL_SCHEDULER_H )
531 msg_Err( p_condvar->p_this,
532 "thread %d: cond_destroy failed at %s:%d (%d:%s)",
533 i_thread, psz_file, i_line, i_result, psz_error );
538 /*****************************************************************************
539 * vlc_thread_create: create a thread, inner version
540 *****************************************************************************
541 * Note that i_priority is only taken into account on platforms supporting
542 * userland real-time priority threads.
543 *****************************************************************************/
544 int __vlc_thread_create( vlc_object_t *p_this, char * psz_file, int i_line,
545 char *psz_name, void * ( *func ) ( void * ),
546 int i_priority, vlc_bool_t b_wait )
550 vlc_mutex_lock( &p_this->object_lock );
555 /* Initialize the wrapper structure */
557 wrapper.p_data = (void *)p_this;
558 getitimer( ITIMER_PROF, &wrapper.itimer );
559 vlc_mutex_init( p_this, &wrapper.lock );
560 vlc_cond_init( p_this, &wrapper.wait );
561 vlc_mutex_lock( &wrapper.lock );
563 /* Alter user-passed data so that we call the wrapper instead
564 * of the real function */
566 func = vlc_thread_wrapper;
569 #if defined( PTH_INIT_IN_PTH_H )
570 p_this->thread_id = pth_spawn( PTH_ATTR_DEFAULT, func, (void *)p_this );
573 #elif defined( ST_INIT_IN_ST_H )
574 p_this->thread_id = st_thread_create( func, (void *)p_this, 1, 0 );
577 #elif defined( WIN32 ) || defined( UNDER_CE )
580 /* When using the MSVCRT C library you have to use the _beginthreadex
581 * function instead of CreateThread, otherwise you'll end up with
582 * memory leaks and the signal functions not working (see Microsoft
583 * Knowledge Base, article 104641) */
585 #if defined( UNDER_CE )
586 (HANDLE)CreateThread( NULL, 0, (PTHREAD_START) func,
587 (void *)p_this, 0, &threadID );
589 (HANDLE)_beginthreadex( NULL, 0, (PTHREAD_START) func,
590 (void *)p_this, 0, &threadID );
594 if ( p_this->thread_id && i_priority )
596 if ( !SetThreadPriority(p_this->thread_id, i_priority) )
598 msg_Warn( p_this, "couldn't set a faster priority" );
603 i_ret = ( p_this->thread_id ? 0 : 1 );
605 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
606 i_ret = pthread_create( &p_this->thread_id, NULL, func, (void *)p_this );
610 struct sched_param param;
611 memset( ¶m, 0, sizeof(struct sched_param) );
612 param.sched_priority = i_priority;
613 if ( pthread_setschedparam( p_this->thread_id, SCHED_RR, ¶m ) )
615 msg_Warn( p_this, "couldn't go to real-time priority (%s:%d)",
621 #elif defined( HAVE_CTHREADS_H )
622 p_this->thread_id = cthread_fork( (cthread_fn_t)func, (any_t)p_this );
625 #elif defined( HAVE_KERNEL_SCHEDULER_H )
626 p_this->thread_id = spawn_thread( (thread_func)func, psz_name,
627 B_NORMAL_PRIORITY, (void *)p_this );
628 i_ret = resume_thread( p_this->thread_id );
635 vlc_cond_wait( &wrapper.wait, &wrapper.lock );
638 vlc_mutex_unlock( &wrapper.lock );
639 vlc_mutex_destroy( &wrapper.lock );
640 vlc_cond_destroy( &wrapper.wait );
647 msg_Dbg( p_this, "waiting for thread completion" );
648 vlc_cond_wait( &p_this->object_wait, &p_this->object_lock );
651 p_this->b_thread = 1;
653 msg_Dbg( p_this, "thread %d (%s) created at priority %d (%s:%d)",
654 (int)p_this->thread_id, psz_name, i_priority,
657 vlc_mutex_unlock( &p_this->object_lock );
662 msg_Err( p_this, "%s thread could not be created at %s:%d (%s)",
663 psz_name, psz_file, i_line, strerror(i_ret) );
665 msg_Err( p_this, "%s thread could not be created at %s:%d",
666 psz_name, psz_file, i_line );
668 vlc_mutex_unlock( &p_this->object_lock );
674 /*****************************************************************************
675 * vlc_thread_set_priority: set the priority of the current thread when we
676 * couldn't set it in vlc_thread_create (for instance for the main thread)
677 *****************************************************************************/
678 int __vlc_thread_set_priority( vlc_object_t *p_this, char * psz_file,
679 int i_line, int i_priority )
681 #if defined( WIN32 ) || defined( UNDER_CE )
682 if ( !SetThreadPriority(GetCurrentThread(), i_priority) )
684 msg_Warn( p_this, "couldn't set a faster priority" );
688 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
691 struct sched_param param;
692 memset( ¶m, 0, sizeof(struct sched_param) );
693 param.sched_priority = i_priority;
694 if ( pthread_setschedparam( pthread_self(), SCHED_RR, ¶m ) )
696 msg_Warn( p_this, "couldn't go to real-time priority (%s:%d)",
709 /*****************************************************************************
710 * vlc_thread_ready: tell the parent thread we were successfully spawned
711 *****************************************************************************/
712 void __vlc_thread_ready( vlc_object_t *p_this )
714 vlc_mutex_lock( &p_this->object_lock );
715 vlc_cond_signal( &p_this->object_wait );
716 vlc_mutex_unlock( &p_this->object_lock );
719 /*****************************************************************************
720 * vlc_thread_join: wait until a thread exits, inner version
721 *****************************************************************************/
722 void __vlc_thread_join( vlc_object_t *p_this, char * psz_file, int i_line )
726 #if defined( PTH_INIT_IN_PTH_H )
727 i_ret = pth_join( p_this->thread_id, NULL );
729 #elif defined( ST_INIT_IN_ST_H )
730 i_ret = st_thread_join( p_this->thread_id, NULL );
732 #elif defined( UNDER_CE )
733 WaitForSingleObject( p_this->thread_id, INFINITE );
735 #elif defined( WIN32 )
736 WaitForSingleObject( p_this->thread_id, INFINITE );
738 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
739 i_ret = pthread_join( p_this->thread_id, NULL );
741 #elif defined( HAVE_CTHREADS_H )
742 cthread_join( p_this->thread_id );
745 #elif defined( HAVE_KERNEL_SCHEDULER_H )
747 wait_for_thread( p_this->thread_id, &exit_value );
754 msg_Err( p_this, "thread_join(%d) failed at %s:%d (%s)",
755 (int)p_this->thread_id, psz_file, i_line,
758 msg_Err( p_this, "thread_join(%d) failed at %s:%d",
759 (int)p_this->thread_id, psz_file, i_line );
764 msg_Dbg( p_this, "thread %d joined (%s:%d)",
765 (int)p_this->thread_id, psz_file, i_line );
768 p_this->b_thread = 0;
771 /*****************************************************************************
772 * vlc_thread_wrapper: wrapper around thread functions used when profiling.
773 *****************************************************************************/
775 static void *vlc_thread_wrapper( void *p_wrapper )
777 /* Put user data in thread-local variables */
778 void * p_data = ((wrapper_t*)p_wrapper)->p_data;
779 vlc_thread_func_t func = ((wrapper_t*)p_wrapper)->func;
781 /* Set the profile timer value */
782 setitimer( ITIMER_PROF, &((wrapper_t*)p_wrapper)->itimer, NULL );
784 /* Tell the calling thread that we don't need its data anymore */
785 vlc_mutex_lock( &((wrapper_t*)p_wrapper)->lock );
786 vlc_cond_signal( &((wrapper_t*)p_wrapper)->wait );
787 vlc_mutex_unlock( &((wrapper_t*)p_wrapper)->lock );
789 /* Call the real function */
790 return func( p_data );