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.36 2003/02/10 16:53:34 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 typedef void *(*vlc_thread_func_t)(void *p_data);
220 /* Wrapper function for profiling */
221 static void * vlc_thread_wrapper ( void *p_wrapper );
223 # if defined( WIN32 ) && !defined( UNDER_CE )
225 # define ITIMER_REAL 1
226 # define ITIMER_PROF 2
230 struct timeval it_value;
231 struct timeval it_interval;
234 int setitimer(int kind, const struct itimerval* itnew, struct itimerval* itold);
235 # endif /* WIN32 && !UNDER_CE */
237 typedef struct wrapper_t
239 /* Data lock access */
243 /* Data used to spawn the real thread */
244 vlc_thread_func_t func;
247 /* Profiling timer passed to the thread */
248 struct itimerval itimer;
254 /*****************************************************************************
255 * vlc_mutex_init: initialize a mutex
256 *****************************************************************************/
257 int __vlc_mutex_init( vlc_object_t *p_this, vlc_mutex_t *p_mutex )
259 p_mutex->p_this = p_this;
261 #if defined( PTH_INIT_IN_PTH_H )
262 return pth_mutex_init( &p_mutex->mutex );
264 #elif defined( ST_INIT_IN_ST_H )
265 p_mutex->mutex = st_mutex_new();
266 return ( p_mutex->mutex == NULL ) ? errno : 0;
268 #elif defined( UNDER_CE )
269 InitializeCriticalSection( &p_mutex->csection );
272 #elif defined( WIN32 )
273 /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
274 * function and have a 100% correct vlc_cond_wait() implementation.
275 * As this function is not available on Win9x, we can use the faster
276 * CriticalSections */
277 if( p_this->p_libvlc->SignalObjectAndWait &&
278 !p_this->p_libvlc->b_fast_mutex )
280 /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
281 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
282 return ( p_mutex->mutex != NULL ? 0 : 1 );
286 p_mutex->mutex = NULL;
287 InitializeCriticalSection( &p_mutex->csection );
291 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
292 # if defined(DEBUG) && defined(SYS_LINUX)
294 /* Create error-checking mutex to detect problems more easily. */
295 pthread_mutexattr_t attr;
298 pthread_mutexattr_init( &attr );
299 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
300 i_result = pthread_mutex_init( &p_mutex->mutex, &attr );
301 pthread_mutexattr_destroy( &attr );
305 return pthread_mutex_init( &p_mutex->mutex, NULL );
307 #elif defined( HAVE_CTHREADS_H )
308 mutex_init( p_mutex );
311 #elif defined( HAVE_KERNEL_SCHEDULER_H )
312 /* check the arguments and whether it's already been initialized */
313 if( p_mutex == NULL )
318 if( p_mutex->init == 9999 )
323 p_mutex->lock = create_sem( 1, "BeMutex" );
324 if( p_mutex->lock < B_NO_ERROR )
329 p_mutex->init = 9999;
335 /*****************************************************************************
336 * vlc_mutex_destroy: destroy a mutex, inner version
337 *****************************************************************************/
338 int __vlc_mutex_destroy( char * psz_file, int i_line, vlc_mutex_t *p_mutex )
341 /* In case of error : */
343 const char * psz_error = "";
345 #if defined( PTH_INIT_IN_PTH_H )
348 #elif defined( ST_INIT_IN_ST_H )
349 i_result = st_mutex_destroy( p_mutex->mutex );
351 #elif defined( UNDER_CE )
352 DeleteCriticalSection( &p_mutex->csection );
355 #elif defined( WIN32 )
358 CloseHandle( p_mutex->mutex );
362 DeleteCriticalSection( &p_mutex->csection );
366 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
367 i_result = pthread_mutex_destroy( &p_mutex->mutex );
370 i_thread = (int)pthread_self();
371 psz_error = strerror(i_result);
374 #elif defined( HAVE_CTHREADS_H )
377 #elif defined( HAVE_KERNEL_SCHEDULER_H )
378 if( p_mutex->init == 9999 )
380 delete_sem( p_mutex->lock );
389 msg_Err( p_mutex->p_this,
390 "thread %d: mutex_destroy failed at %s:%d (%d:%s)",
391 i_thread, psz_file, i_line, i_result, psz_error );
396 /*****************************************************************************
397 * vlc_cond_init: initialize a condition
398 *****************************************************************************/
399 int __vlc_cond_init( vlc_object_t *p_this, vlc_cond_t *p_condvar )
401 p_condvar->p_this = p_this;
403 #if defined( PTH_INIT_IN_PTH_H )
404 return pth_cond_init( &p_condvar->cond );
406 #elif defined( ST_INIT_IN_ST_H )
407 p_condvar->cond = st_cond_new();
408 return ( p_condvar->cond == NULL ) ? errno : 0;
410 #elif defined( UNDER_CE )
411 /* Initialize counter */
412 p_condvar->i_waiting_threads = 0;
414 /* Create an auto-reset event. */
415 p_condvar->event = CreateEvent( NULL, /* no security */
416 FALSE, /* auto-reset event */
417 FALSE, /* start non-signaled */
418 NULL ); /* unnamed */
419 return !p_condvar->event;
421 #elif defined( WIN32 )
422 /* Initialize counter */
423 p_condvar->i_waiting_threads = 0;
426 p_condvar->i_win9x_cv = p_this->p_libvlc->i_win9x_cv;
427 p_condvar->SignalObjectAndWait = p_this->p_libvlc->SignalObjectAndWait;
429 if( (p_condvar->SignalObjectAndWait && !p_this->p_libvlc->b_fast_mutex)
430 || p_condvar->i_win9x_cv == 0 )
432 /* Create an auto-reset event. */
433 p_condvar->event = CreateEvent( NULL, /* no security */
434 FALSE, /* auto-reset event */
435 FALSE, /* start non-signaled */
436 NULL ); /* unnamed */
438 p_condvar->semaphore = NULL;
439 return !p_condvar->event;
443 p_condvar->semaphore = CreateSemaphore( NULL, /* no security */
444 0, /* initial count */
445 0x7fffffff, /* max count */
446 NULL ); /* unnamed */
448 if( p_condvar->i_win9x_cv == 1 )
449 /* Create a manual-reset event initially signaled. */
450 p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
452 /* Create a auto-reset event. */
453 p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
455 InitializeCriticalSection( &p_condvar->csection );
457 return !p_condvar->semaphore || !p_condvar->event;
460 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
461 return pthread_cond_init( &p_condvar->cond, NULL );
463 #elif defined( HAVE_CTHREADS_H )
464 /* condition_init() */
465 spin_lock_init( &p_condvar->lock );
466 cthread_queue_init( &p_condvar->queue );
468 p_condvar->implications = 0;
472 #elif defined( HAVE_KERNEL_SCHEDULER_H )
478 if( p_condvar->init == 9999 )
483 p_condvar->thread = -1;
484 p_condvar->init = 9999;
489 /*****************************************************************************
490 * vlc_cond_destroy: destroy a condition, inner version
491 *****************************************************************************/
492 int __vlc_cond_destroy( char * psz_file, int i_line, vlc_cond_t *p_condvar )
495 /* In case of error : */
497 const char * psz_error = "";
499 #if defined( PTH_INIT_IN_PTH_H )
502 #elif defined( ST_INIT_IN_ST_H )
503 i_result = st_cond_destroy( p_condvar->cond );
505 #elif defined( UNDER_CE )
506 i_result = !CloseHandle( p_condvar->event );
508 #elif defined( WIN32 )
509 if( !p_condvar->semaphore )
510 i_result = !CloseHandle( p_condvar->event );
512 i_result = !CloseHandle( p_condvar->event )
513 || !CloseHandle( p_condvar->semaphore );
515 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
516 i_result = pthread_cond_destroy( &p_condvar->cond );
519 i_thread = (int)pthread_self();
520 psz_error = strerror(i_result);
523 #elif defined( HAVE_CTHREADS_H )
526 #elif defined( HAVE_KERNEL_SCHEDULER_H )
533 msg_Err( p_condvar->p_this,
534 "thread %d: cond_destroy failed at %s:%d (%d:%s)",
535 i_thread, psz_file, i_line, i_result, psz_error );
540 /*****************************************************************************
541 * vlc_thread_create: create a thread, inner version
542 *****************************************************************************
543 * Note that i_priority is only taken into account on platforms supporting
544 * userland real-time priority threads.
545 *****************************************************************************/
546 int __vlc_thread_create( vlc_object_t *p_this, char * psz_file, int i_line,
547 char *psz_name, void * ( *func ) ( void * ),
548 int i_priority, vlc_bool_t b_wait )
553 vlc_mutex_lock( &p_this->object_lock );
558 /* Initialize the wrapper structure */
560 wrapper.p_data = (void *)p_this;
561 getitimer( ITIMER_PROF, &wrapper.itimer );
562 vlc_mutex_init( p_this, &wrapper.lock );
563 vlc_cond_init( p_this, &wrapper.wait );
564 vlc_mutex_lock( &wrapper.lock );
566 /* Alter user-passed data so that we call the wrapper instead
567 * of the real function */
569 func = vlc_thread_wrapper;
571 p_data = (void *)p_this;
574 #if defined( PTH_INIT_IN_PTH_H )
575 p_this->thread_id = pth_spawn( PTH_ATTR_DEFAULT, func, p_data );
578 #elif defined( ST_INIT_IN_ST_H )
579 p_this->thread_id = st_thread_create( func, p_data, 1, 0 );
582 #elif defined( WIN32 ) || defined( UNDER_CE )
585 /* When using the MSVCRT C library you have to use the _beginthreadex
586 * function instead of CreateThread, otherwise you'll end up with
587 * memory leaks and the signal functions not working (see Microsoft
588 * Knowledge Base, article 104641) */
590 #if defined( UNDER_CE )
591 (HANDLE)CreateThread( NULL, 0, (PTHREAD_START) func,
592 p_data, 0, &threadID );
594 (HANDLE)_beginthreadex( NULL, 0, (PTHREAD_START) func,
595 p_data, 0, &threadID );
599 if ( p_this->thread_id && i_priority )
601 if ( !SetThreadPriority(p_this->thread_id, i_priority) )
603 msg_Warn( p_this, "couldn't set a faster priority" );
608 i_ret = ( p_this->thread_id ? 0 : 1 );
610 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
611 i_ret = pthread_create( &p_this->thread_id, NULL, func, p_data );
616 struct sched_param param;
617 memset( ¶m, 0, sizeof(struct sched_param) );
618 param.sched_priority = i_priority;
619 if ( (i_error = pthread_setschedparam( p_this->thread_id,
620 SCHED_RR, ¶m )) )
622 msg_Warn( p_this, "couldn't go to real-time priority (%s:%d): %s",
623 psz_file, i_line, strerror(i_error) );
629 #elif defined( HAVE_CTHREADS_H )
630 p_this->thread_id = cthread_fork( (cthread_fn_t)func, (any_t)p_data );
633 #elif defined( HAVE_KERNEL_SCHEDULER_H )
634 p_this->thread_id = spawn_thread( (thread_func)func, psz_name,
635 i_priority, p_data );
636 i_ret = resume_thread( p_this->thread_id );
643 vlc_cond_wait( &wrapper.wait, &wrapper.lock );
646 vlc_mutex_unlock( &wrapper.lock );
647 vlc_mutex_destroy( &wrapper.lock );
648 vlc_cond_destroy( &wrapper.wait );
655 msg_Dbg( p_this, "waiting for thread completion" );
656 vlc_cond_wait( &p_this->object_wait, &p_this->object_lock );
659 p_this->b_thread = 1;
661 msg_Dbg( p_this, "thread %d (%s) created at priority %d (%s:%d)",
662 (int)p_this->thread_id, psz_name, i_priority,
665 vlc_mutex_unlock( &p_this->object_lock );
670 msg_Err( p_this, "%s thread could not be created at %s:%d (%s)",
671 psz_name, psz_file, i_line, strerror(i_ret) );
673 msg_Err( p_this, "%s thread could not be created at %s:%d",
674 psz_name, psz_file, i_line );
676 vlc_mutex_unlock( &p_this->object_lock );
682 /*****************************************************************************
683 * vlc_thread_set_priority: set the priority of the current thread when we
684 * couldn't set it in vlc_thread_create (for instance for the main thread)
685 *****************************************************************************/
686 int __vlc_thread_set_priority( vlc_object_t *p_this, char * psz_file,
687 int i_line, int i_priority )
689 #if defined( WIN32 ) || defined( UNDER_CE )
690 if ( !SetThreadPriority(GetCurrentThread(), i_priority) )
692 msg_Warn( p_this, "couldn't set a faster priority" );
696 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
700 struct sched_param param;
701 memset( ¶m, 0, sizeof(struct sched_param) );
702 param.sched_priority = i_priority;
703 if ( (i_error = pthread_setschedparam( pthread_self(),
704 SCHED_RR, ¶m )) )
706 msg_Warn( p_this, "couldn't go to real-time priority (%s:%d): %s",
707 psz_file, i_line, strerror(i_error) );
717 /*****************************************************************************
718 * vlc_thread_ready: tell the parent thread we were successfully spawned
719 *****************************************************************************/
720 void __vlc_thread_ready( vlc_object_t *p_this )
722 vlc_mutex_lock( &p_this->object_lock );
723 vlc_cond_signal( &p_this->object_wait );
724 vlc_mutex_unlock( &p_this->object_lock );
727 /*****************************************************************************
728 * vlc_thread_join: wait until a thread exits, inner version
729 *****************************************************************************/
730 void __vlc_thread_join( vlc_object_t *p_this, char * psz_file, int i_line )
734 #if defined( PTH_INIT_IN_PTH_H )
735 i_ret = pth_join( p_this->thread_id, NULL );
737 #elif defined( ST_INIT_IN_ST_H )
738 i_ret = st_thread_join( p_this->thread_id, NULL );
740 #elif defined( UNDER_CE )
741 WaitForSingleObject( p_this->thread_id, INFINITE );
743 #elif defined( WIN32 )
744 WaitForSingleObject( p_this->thread_id, INFINITE );
746 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
747 i_ret = pthread_join( p_this->thread_id, NULL );
749 #elif defined( HAVE_CTHREADS_H )
750 cthread_join( p_this->thread_id );
753 #elif defined( HAVE_KERNEL_SCHEDULER_H )
755 wait_for_thread( p_this->thread_id, &exit_value );
762 msg_Err( p_this, "thread_join(%d) failed at %s:%d (%s)",
763 (int)p_this->thread_id, psz_file, i_line,
766 msg_Err( p_this, "thread_join(%d) failed at %s:%d",
767 (int)p_this->thread_id, psz_file, i_line );
772 msg_Dbg( p_this, "thread %d joined (%s:%d)",
773 (int)p_this->thread_id, psz_file, i_line );
776 p_this->b_thread = 0;
779 /*****************************************************************************
780 * vlc_thread_wrapper: wrapper around thread functions used when profiling.
781 *****************************************************************************/
783 static void *vlc_thread_wrapper( void *p_wrapper )
785 /* Put user data in thread-local variables */
786 void * p_data = ((wrapper_t*)p_wrapper)->p_data;
787 vlc_thread_func_t func = ((wrapper_t*)p_wrapper)->func;
789 /* Set the profile timer value */
790 setitimer( ITIMER_PROF, &((wrapper_t*)p_wrapper)->itimer, NULL );
792 /* Tell the calling thread that we don't need its data anymore */
793 vlc_mutex_lock( &((wrapper_t*)p_wrapper)->lock );
794 vlc_cond_signal( &((wrapper_t*)p_wrapper)->wait );
795 vlc_mutex_unlock( &((wrapper_t*)p_wrapper)->lock );
797 /* Call the real function */
798 return func( p_data );