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.21 2002/10/04 18:07:22 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 static vlc_namedmutex_t *p_named_list = NULL;
63 static vlc_mutex_t named_lock;
65 /*****************************************************************************
66 * vlc_threads_init: initialize threads system
67 *****************************************************************************
68 * This function requires lazy initialization of a global lock in order to
69 * keep the library really thread-safe. Some architectures don't support this
70 * and thus do not guarantee the complete reentrancy.
71 *****************************************************************************/
72 int __vlc_threads_init( vlc_object_t *p_this )
74 static volatile int i_status = VLC_THREADS_UNINITIALIZED;
76 libvlc_t *p_libvlc = (libvlc_t *)p_this;
77 int i_ret = VLC_SUCCESS;
79 /* If we have lazy mutex initialization, use it. Otherwise, we just
80 * hope nothing wrong happens. */
81 #if defined( PTH_INIT_IN_PTH_H )
82 #elif defined( ST_INIT_IN_ST_H )
83 #elif defined( WIN32 )
85 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
86 pthread_mutex_lock( &once_mutex );
87 #elif defined( HAVE_CTHREADS_H )
88 #elif defined( HAVE_KERNEL_SCHEDULER_H )
91 if( i_status == VLC_THREADS_UNINITIALIZED )
93 i_status = VLC_THREADS_PENDING;
95 /* We should be safe now. Do all the initialization stuff we want. */
96 vlc_object_create( p_libvlc, VLC_OBJECT_ROOT );
97 p_libvlc->b_ready = VLC_FALSE;
99 #if defined( PTH_INIT_IN_PTH_H )
102 #elif defined( ST_INIT_IN_ST_H )
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 )
131 vlc_mutex_init( p_libvlc, &named_lock );
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( WIN32 )
156 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
157 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
158 pthread_mutex_unlock( &once_mutex );
159 #elif defined( HAVE_CTHREADS_H )
160 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
161 #elif defined( HAVE_KERNEL_SCHEDULER_H )
162 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
165 if( i_status != VLC_THREADS_READY )
173 /*****************************************************************************
174 * vlc_threads_end: stop threads system
175 *****************************************************************************
176 * FIXME: This function is far from being threadsafe. We should undo exactly
177 * what we did above in vlc_threads_init.
178 *****************************************************************************/
179 int __vlc_threads_end( vlc_object_t *p_this )
181 #if defined( PTH_INIT_IN_PTH_H )
183 if( i_initializations == 0 )
188 #elif defined( ST_INIT_IN_ST_H )
191 #elif defined( WIN32 )
194 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
195 pthread_mutex_lock( &once_mutex );
197 pthread_mutex_unlock( &once_mutex );
199 #elif defined( HAVE_CTHREADS_H )
202 #elif defined( HAVE_KERNEL_SCHEDULER_H )
209 /*****************************************************************************
210 * Prototype for GPROF wrapper
211 *****************************************************************************/
213 /* Wrapper function for profiling */
214 static void * vlc_thread_wrapper ( void *p_wrapper );
218 # define ITIMER_REAL 1
219 # define ITIMER_PROF 2
223 struct timeval it_value;
224 struct timeval it_interval;
227 int setitimer(int kind, const struct itimerval* itnew, struct itimerval* itold);
230 typedef struct wrapper_t
232 /* Data lock access */
236 /* Data used to spawn the real thread */
237 vlc_thread_func_t func;
240 /* Profiling timer passed to the thread */
241 struct itimerval itimer;
247 /*****************************************************************************
248 * vlc_mutex_init: initialize a mutex
249 *****************************************************************************/
250 int __vlc_mutex_init( vlc_object_t *p_this, vlc_mutex_t *p_mutex )
252 p_mutex->p_this = p_this;
254 #if defined( PTH_INIT_IN_PTH_H )
255 return pth_mutex_init( &p_mutex->mutex );
257 #elif defined( ST_INIT_IN_ST_H )
258 p_mutex->mutex = st_mutex_new();
259 return ( p_mutex->mutex == NULL ) ? errno : 0;
261 #elif defined( WIN32 )
262 /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
263 * function and have a 100% correct vlc_cond_wait() implementation.
264 * As this function is not available on Win9x, we can use the faster
265 * CriticalSections */
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 );
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_need: create a global mutex from its name
326 *****************************************************************************/
327 vlc_mutex_t * __vlc_mutex_need( vlc_object_t *p_this, char *psz_name )
329 vlc_namedmutex_t *p_named;
331 vlc_mutex_lock( &named_lock );
333 p_named = p_named_list;
336 if( !strcmp( psz_name, p_named->psz_name ) )
340 p_named = p_named->p_next;
349 p_named = malloc( sizeof( vlc_namedmutex_t ) );
350 vlc_mutex_init( p_this, &p_named->lock );
351 p_named->psz_name = strdup( psz_name );
352 p_named->i_usage = 1;
353 p_named->p_next = p_named_list;
354 p_named_list = p_named;
357 vlc_mutex_unlock( &named_lock );
359 return &p_named->lock;
362 /*****************************************************************************
363 * vlc_mutex_unneed: destroy a global mutex from its name
364 *****************************************************************************/
365 void __vlc_mutex_unneed( vlc_object_t *p_this, char *psz_name )
367 vlc_namedmutex_t *p_named, *p_prev;
369 vlc_mutex_lock( &named_lock );
371 p_named = p_named_list;
375 if( !strcmp( psz_name, p_named->psz_name ) )
380 p_named = p_named->p_next;
387 if( p_named->i_usage <= 0 )
389 /* Unlink named mutex */
392 p_prev->p_next = p_named->p_next;
396 p_named_list = p_named->p_next;
399 /* Release this lock as soon as possible */
400 vlc_mutex_unlock( &named_lock );
402 vlc_mutex_destroy( &p_named->lock );
403 free( p_named->psz_name );
411 msg_Err( p_this, "no named mutex called %s", psz_name );
414 vlc_mutex_unlock( &named_lock );
417 /*****************************************************************************
418 * vlc_mutex_destroy: destroy a mutex, inner version
419 *****************************************************************************/
420 int __vlc_mutex_destroy( char * psz_file, int i_line, vlc_mutex_t *p_mutex )
423 /* In case of error : */
425 const char * psz_error = "";
427 #if defined( PTH_INIT_IN_PTH_H )
430 #elif defined( ST_INIT_IN_ST_H )
431 i_result = st_mutex_destroy( p_mutex->mutex );
433 #elif defined( WIN32 )
436 CloseHandle( p_mutex->mutex );
440 DeleteCriticalSection( &p_mutex->csection );
444 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
445 i_result = pthread_mutex_destroy( &p_mutex->mutex );
448 i_thread = (int)pthread_self();
449 psz_error = strerror(i_result);
452 #elif defined( HAVE_CTHREADS_H )
455 #elif defined( HAVE_KERNEL_SCHEDULER_H )
456 if( p_mutex->init == 9999 )
458 delete_sem( p_mutex->lock );
467 msg_Err( p_mutex->p_this,
468 "thread %d: mutex_destroy failed at %s:%d (%d:%s)",
469 i_thread, psz_file, i_line, i_result, psz_error );
474 /*****************************************************************************
475 * vlc_cond_init: initialize a condition
476 *****************************************************************************/
477 int __vlc_cond_init( vlc_object_t *p_this, vlc_cond_t *p_condvar )
479 p_condvar->p_this = p_this;
481 #if defined( PTH_INIT_IN_PTH_H )
482 return pth_cond_init( &p_condvar->cond );
484 #elif defined( ST_INIT_IN_ST_H )
485 p_condvar->cond = st_cond_new();
486 return ( p_condvar->cond == NULL ) ? errno : 0;
488 #elif defined( WIN32 )
489 /* Initialize counter */
490 p_condvar->i_waiting_threads = 0;
493 p_condvar->i_win9x_cv = p_this->p_libvlc->i_win9x_cv;
494 p_condvar->SignalObjectAndWait = p_this->p_libvlc->SignalObjectAndWait;
496 if( (p_condvar->SignalObjectAndWait && !p_this->p_libvlc->b_fast_mutex)
497 || p_condvar->i_win9x_cv == 0 )
499 /* Create an auto-reset event. */
500 p_condvar->event = CreateEvent( NULL, /* no security */
501 FALSE, /* auto-reset event */
502 FALSE, /* start non-signaled */
503 NULL ); /* unnamed */
505 p_condvar->semaphore = NULL;
506 return !p_condvar->event;
510 p_condvar->semaphore = CreateSemaphore( NULL, /* no security */
511 0, /* initial count */
512 0x7fffffff, /* max count */
513 NULL ); /* unnamed */
515 if( p_condvar->i_win9x_cv == 1 )
516 /* Create a manual-reset event initially signaled. */
517 p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
519 /* Create a auto-reset event. */
520 p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
522 InitializeCriticalSection( &p_condvar->csection );
524 return !p_condvar->semaphore || !p_condvar->event;
527 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
528 return pthread_cond_init( &p_condvar->cond, NULL );
530 #elif defined( HAVE_CTHREADS_H )
531 /* condition_init() */
532 spin_lock_init( &p_condvar->lock );
533 cthread_queue_init( &p_condvar->queue );
535 p_condvar->implications = 0;
539 #elif defined( HAVE_KERNEL_SCHEDULER_H )
545 if( p_condvar->init == 9999 )
550 p_condvar->thread = -1;
551 p_condvar->init = 9999;
556 /*****************************************************************************
557 * vlc_cond_destroy: destroy a condition, inner version
558 *****************************************************************************/
559 int __vlc_cond_destroy( char * psz_file, int i_line, vlc_cond_t *p_condvar )
562 /* In case of error : */
564 const char * psz_error = "";
566 #if defined( PTH_INIT_IN_PTH_H )
569 #elif defined( ST_INIT_IN_ST_H )
570 i_result = st_cond_destroy( p_condvar->cond );
572 #elif defined( WIN32 )
573 if( !p_condvar->semaphore )
574 i_result = !CloseHandle( p_condvar->event );
576 i_result = !CloseHandle( p_condvar->event )
577 || !CloseHandle( p_condvar->semaphore );
579 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
580 i_result = pthread_cond_destroy( &p_condvar->cond );
583 i_thread = (int)pthread_self();
584 psz_error = strerror(i_result);
587 #elif defined( HAVE_CTHREADS_H )
590 #elif defined( HAVE_KERNEL_SCHEDULER_H )
597 msg_Err( p_condvar->p_this,
598 "thread %d: cond_destroy failed at %s:%d (%d:%s)",
599 i_thread, psz_file, i_line, i_result, psz_error );
604 /*****************************************************************************
605 * vlc_thread_create: create a thread, inner version
606 *****************************************************************************
607 * Note that i_priority is only taken into account on platforms supporting
608 * userland real-time priority threads.
609 *****************************************************************************/
610 int __vlc_thread_create( vlc_object_t *p_this, char * psz_file, int i_line,
611 char *psz_name, void * ( *func ) ( void * ),
612 int i_priority, vlc_bool_t b_wait )
616 vlc_mutex_lock( &p_this->object_lock );
621 /* Initialize the wrapper structure */
623 wrapper.p_data = (void *)p_this;
624 getitimer( ITIMER_PROF, &wrapper.itimer );
625 vlc_mutex_init( p_this, &wrapper.lock );
626 vlc_cond_init( p_this, &wrapper.wait );
627 vlc_mutex_lock( &wrapper.lock );
629 /* Alter user-passed data so that we call the wrapper instead
630 * of the real function */
632 func = vlc_thread_wrapper;
635 #if defined( PTH_INIT_IN_PTH_H )
636 p_this->thread_id = pth_spawn( PTH_ATTR_DEFAULT, func, (void *)p_this );
639 #elif defined( ST_INIT_IN_ST_H )
640 p_this->thread_id = st_thread_create( func, (void *)p_this, 1, 0 );
643 #elif defined( WIN32 )
646 /* When using the MSVCRT C library you have to use the _beginthreadex
647 * function instead of CreateThread, otherwise you'll end up with
648 * memory leaks and the signal functions not working */
650 (HANDLE)_beginthreadex( NULL, 0, (PTHREAD_START) func,
651 (void *)p_this, 0, &threadID );
654 if ( p_this->thread_id && i_priority )
656 if ( !SetThreadPriority(p_this->thread_id, i_priority) )
658 msg_Warn( p_this, "couldn't set a faster priority" );
663 i_ret = ( p_this->thread_id ? 0 : 1 );
665 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
666 i_ret = pthread_create( &p_this->thread_id, NULL, func, (void *)p_this );
670 struct sched_param param;
671 memset( ¶m, 0, sizeof(struct sched_param) );
672 param.sched_priority = i_priority;
673 if ( pthread_setschedparam( p_this->thread_id, SCHED_RR, ¶m ) )
675 msg_Warn( p_this, "couldn't go to real-time priority" );
680 #elif defined( HAVE_CTHREADS_H )
681 p_this->thread_id = cthread_fork( (cthread_fn_t)func, (any_t)p_this );
684 #elif defined( HAVE_KERNEL_SCHEDULER_H )
685 p_this->thread_id = spawn_thread( (thread_func)func, psz_name,
686 B_NORMAL_PRIORITY, (void *)p_this );
687 i_ret = resume_thread( p_this->thread_id );
694 vlc_cond_wait( &wrapper.wait, &wrapper.lock );
697 vlc_mutex_unlock( &wrapper.lock );
698 vlc_mutex_destroy( &wrapper.lock );
699 vlc_cond_destroy( &wrapper.wait );
706 msg_Dbg( p_this, "waiting for thread completion" );
707 vlc_cond_wait( &p_this->object_wait, &p_this->object_lock );
710 p_this->b_thread = 1;
712 msg_Dbg( p_this, "thread %d (%s) created at priority %d (%s:%d)",
713 p_this->thread_id, psz_name, i_priority,
716 vlc_mutex_unlock( &p_this->object_lock );
720 msg_Err( p_this, "%s thread could not be created at %s:%d (%s)",
721 psz_name, psz_file, i_line, strerror(i_ret) );
722 vlc_mutex_unlock( &p_this->object_lock );
728 /*****************************************************************************
729 * vlc_thread_ready: tell the parent thread we were successfully spawned
730 *****************************************************************************/
731 void __vlc_thread_ready( vlc_object_t *p_this )
733 vlc_mutex_lock( &p_this->object_lock );
734 vlc_cond_signal( &p_this->object_wait );
735 vlc_mutex_unlock( &p_this->object_lock );
738 /*****************************************************************************
739 * vlc_thread_join: wait until a thread exits, inner version
740 *****************************************************************************/
741 void __vlc_thread_join( vlc_object_t *p_this, char * psz_file, int i_line )
745 #if defined( PTH_INIT_IN_PTH_H )
746 i_ret = pth_join( p_this->thread_id, NULL );
748 #elif defined( ST_INIT_IN_ST_H )
749 i_ret = st_thread_join( p_this->thread_id, NULL );
751 #elif defined( WIN32 )
752 WaitForSingleObject( p_this->thread_id, INFINITE );
754 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
755 i_ret = pthread_join( p_this->thread_id, NULL );
757 #elif defined( HAVE_CTHREADS_H )
758 cthread_join( p_this->thread_id );
761 #elif defined( HAVE_KERNEL_SCHEDULER_H )
763 wait_for_thread( p_this->thread_id, &exit_value );
769 msg_Err( p_this, "thread_join(%d) failed at %s:%d (%s)",
770 p_this->thread_id, psz_file, i_line, strerror(i_ret) );
774 msg_Dbg( p_this, "thread %d joined (%s:%d)",
775 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 );