1 /*****************************************************************************
2 * threads.c : threads implementation for the VideoLAN client
3 *****************************************************************************
4 * Copyright (C) 1999-2004 the VideoLAN team
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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, 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 unsigned i_initializations = 0;
39 static volatile int i_status = VLC_THREADS_UNINITIALIZED;
40 static vlc_object_t *p_root;
42 #if defined( PTH_INIT_IN_PTH_H )
43 #elif defined( ST_INIT_IN_ST_H )
44 #elif defined( UNDER_CE )
45 #elif defined( WIN32 )
46 #elif defined( HAVE_KERNEL_SCHEDULER_H )
47 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
48 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
49 #elif defined( HAVE_CTHREADS_H )
52 /*****************************************************************************
53 * Global variable for named mutexes
54 *****************************************************************************/
55 typedef struct vlc_namedmutex_t vlc_namedmutex_t;
56 struct vlc_namedmutex_t
62 vlc_namedmutex_t *p_next;
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 libvlc_global_data_t *p_libvlc_global = (libvlc_global_data_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 )
83 #elif defined( HAVE_KERNEL_SCHEDULER_H )
84 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
85 pthread_mutex_lock( &once_mutex );
86 #elif defined( HAVE_CTHREADS_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 p_libvlc_global->b_ready = VLC_FALSE;
96 #if defined( PTH_INIT_IN_PTH_H )
97 i_ret = ( pth_init() == FALSE );
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 )
111 /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
112 hInstLib = LoadLibrary( "kernel32" );
115 p_libvlc_global->SignalObjectAndWait =
116 (SIGNALOBJECTANDWAIT)GetProcAddress( hInstLib,
117 "SignalObjectAndWait" );
122 p_libvlc_global->SignalObjectAndWait = NULL;
125 p_libvlc_global->b_fast_mutex = 0;
126 p_libvlc_global->i_win9x_cv = 0;
128 #elif defined( HAVE_KERNEL_SCHEDULER_H )
129 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
130 #elif defined( HAVE_CTHREADS_H )
133 p_root = vlc_object_create( p_libvlc_global, VLC_OBJECT_ROOT );
139 i_status = VLC_THREADS_ERROR;
144 i_status = VLC_THREADS_READY;
149 /* Just increment the initialization count */
153 /* If we have lazy mutex initialization support, unlock the mutex;
154 * otherwize, do a naive wait loop. */
155 #if defined( PTH_INIT_IN_PTH_H )
156 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
157 #elif defined( ST_INIT_IN_ST_H )
158 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
159 #elif defined( UNDER_CE )
160 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
161 #elif defined( WIN32 )
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 );
165 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
166 pthread_mutex_unlock( &once_mutex );
167 #elif defined( HAVE_CTHREADS_H )
168 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
171 if( i_status != VLC_THREADS_READY )
179 /*****************************************************************************
180 * vlc_threads_end: stop threads system
181 *****************************************************************************
182 * FIXME: This function is far from being threadsafe.
183 *****************************************************************************/
184 int __vlc_threads_end( vlc_object_t *p_this )
186 #if defined( PTH_INIT_IN_PTH_H )
187 #elif defined( ST_INIT_IN_ST_H )
188 #elif defined( UNDER_CE )
189 #elif defined( WIN32 )
190 #elif defined( HAVE_KERNEL_SCHEDULER_H )
191 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
192 pthread_mutex_lock( &once_mutex );
193 #elif defined( HAVE_CTHREADS_H )
196 if( i_initializations == 0 )
200 if( i_initializations == 0 )
202 i_status = VLC_THREADS_UNINITIALIZED;
203 vlc_object_destroy( p_root );
206 #if defined( PTH_INIT_IN_PTH_H )
207 if( i_initializations == 0 )
209 return ( pth_kill() == FALSE );
212 #elif defined( ST_INIT_IN_ST_H )
213 #elif defined( UNDER_CE )
214 #elif defined( WIN32 )
215 #elif defined( HAVE_KERNEL_SCHEDULER_H )
216 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
217 pthread_mutex_unlock( &once_mutex );
218 #elif defined( HAVE_CTHREADS_H )
223 /*****************************************************************************
224 * vlc_mutex_init: initialize a mutex
225 *****************************************************************************/
226 int __vlc_mutex_init( vlc_object_t *p_this, vlc_mutex_t *p_mutex )
228 p_mutex->p_this = p_this;
230 #if defined( PTH_INIT_IN_PTH_H )
231 return ( pth_mutex_init( &p_mutex->mutex ) == FALSE );
233 #elif defined( ST_INIT_IN_ST_H )
234 p_mutex->mutex = st_mutex_new();
235 return ( p_mutex->mutex == NULL ) ? errno : 0;
237 #elif defined( UNDER_CE )
238 InitializeCriticalSection( &p_mutex->csection );
241 #elif defined( WIN32 )
242 /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
243 * function and have a 100% correct vlc_cond_wait() implementation.
244 * As this function is not available on Win9x, we can use the faster
245 * CriticalSections */
246 if( p_this->p_libvlc_global->SignalObjectAndWait &&
247 !p_this->p_libvlc_global->b_fast_mutex )
249 /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
250 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
251 return ( p_mutex->mutex != NULL ? 0 : 1 );
255 p_mutex->mutex = NULL;
256 InitializeCriticalSection( &p_mutex->csection );
260 #elif defined( HAVE_KERNEL_SCHEDULER_H )
261 /* check the arguments and whether it's already been initialized */
262 if( p_mutex == NULL )
267 if( p_mutex->init == 9999 )
272 p_mutex->lock = create_sem( 1, "BeMutex" );
273 if( p_mutex->lock < B_NO_ERROR )
278 p_mutex->init = 9999;
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 );
304 /*****************************************************************************
305 * vlc_mutex_destroy: destroy a mutex, inner version
306 *****************************************************************************/
307 int __vlc_mutex_destroy( char * psz_file, int i_line, vlc_mutex_t *p_mutex )
310 /* In case of error : */
312 const char * psz_error = "";
314 #if defined( PTH_INIT_IN_PTH_H )
317 #elif defined( ST_INIT_IN_ST_H )
318 i_result = st_mutex_destroy( p_mutex->mutex );
320 #elif defined( UNDER_CE )
321 DeleteCriticalSection( &p_mutex->csection );
324 #elif defined( WIN32 )
327 CloseHandle( p_mutex->mutex );
331 DeleteCriticalSection( &p_mutex->csection );
335 #elif defined( HAVE_KERNEL_SCHEDULER_H )
336 if( p_mutex->init == 9999 )
338 delete_sem( p_mutex->lock );
344 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
345 i_result = pthread_mutex_destroy( &p_mutex->mutex );
348 i_thread = (int)pthread_self();
349 psz_error = strerror(i_result);
352 #elif defined( HAVE_CTHREADS_H )
359 msg_Err( p_mutex->p_this,
360 "thread %d: mutex_destroy failed at %s:%d (%d:%s)",
361 i_thread, psz_file, i_line, i_result, psz_error );
366 /*****************************************************************************
367 * vlc_cond_init: initialize a condition
368 *****************************************************************************/
369 int __vlc_cond_init( vlc_object_t *p_this, vlc_cond_t *p_condvar )
371 p_condvar->p_this = p_this;
373 #if defined( PTH_INIT_IN_PTH_H )
374 return ( pth_cond_init( &p_condvar->cond ) == FALSE );
376 #elif defined( ST_INIT_IN_ST_H )
377 p_condvar->cond = st_cond_new();
378 return ( p_condvar->cond == NULL ) ? errno : 0;
380 #elif defined( UNDER_CE )
381 /* Initialize counter */
382 p_condvar->i_waiting_threads = 0;
384 /* Create an auto-reset event. */
385 p_condvar->event = CreateEvent( NULL, /* no security */
386 FALSE, /* auto-reset event */
387 FALSE, /* start non-signaled */
388 NULL ); /* unnamed */
389 return !p_condvar->event;
391 #elif defined( WIN32 )
392 /* Initialize counter */
393 p_condvar->i_waiting_threads = 0;
396 p_condvar->i_win9x_cv = p_this->p_libvlc_global->i_win9x_cv;
397 p_condvar->SignalObjectAndWait = p_this->p_libvlc_global->SignalObjectAndWait;
399 if( (p_condvar->SignalObjectAndWait &&
400 !p_this->p_libvlc_global->b_fast_mutex)
401 || p_condvar->i_win9x_cv == 0 )
403 /* Create an auto-reset event. */
404 p_condvar->event = CreateEvent( NULL, /* no security */
405 FALSE, /* auto-reset event */
406 FALSE, /* start non-signaled */
407 NULL ); /* unnamed */
409 p_condvar->semaphore = NULL;
410 return !p_condvar->event;
414 p_condvar->semaphore = CreateSemaphore( NULL, /* no security */
415 0, /* initial count */
416 0x7fffffff, /* max count */
417 NULL ); /* unnamed */
419 if( p_condvar->i_win9x_cv == 1 )
420 /* Create a manual-reset event initially signaled. */
421 p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
423 /* Create a auto-reset event. */
424 p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
426 InitializeCriticalSection( &p_condvar->csection );
428 return !p_condvar->semaphore || !p_condvar->event;
431 #elif defined( HAVE_KERNEL_SCHEDULER_H )
437 if( p_condvar->init == 9999 )
442 p_condvar->thread = -1;
443 p_condvar->init = 9999;
446 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
447 return pthread_cond_init( &p_condvar->cond, NULL );
449 #elif defined( HAVE_CTHREADS_H )
450 /* condition_init() */
451 spin_lock_init( &p_condvar->lock );
452 cthread_queue_init( &p_condvar->queue );
454 p_condvar->implications = 0;
461 /*****************************************************************************
462 * vlc_cond_destroy: destroy a condition, inner version
463 *****************************************************************************/
464 int __vlc_cond_destroy( char * psz_file, int i_line, vlc_cond_t *p_condvar )
467 /* In case of error : */
469 const char * psz_error = "";
471 #if defined( PTH_INIT_IN_PTH_H )
474 #elif defined( ST_INIT_IN_ST_H )
475 i_result = st_cond_destroy( p_condvar->cond );
477 #elif defined( UNDER_CE )
478 i_result = !CloseHandle( p_condvar->event );
480 #elif defined( WIN32 )
481 if( !p_condvar->semaphore )
482 i_result = !CloseHandle( p_condvar->event );
484 i_result = !CloseHandle( p_condvar->event )
485 || !CloseHandle( p_condvar->semaphore );
487 if( p_condvar->semaphore != NULL )
488 DeleteCriticalSection( &p_condvar->csection );
490 #elif defined( HAVE_KERNEL_SCHEDULER_H )
494 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
495 i_result = pthread_cond_destroy( &p_condvar->cond );
498 i_thread = (int)pthread_self();
499 psz_error = strerror(i_result);
502 #elif defined( HAVE_CTHREADS_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 )
527 void *p_data = (void *)p_this;
529 vlc_mutex_lock( &p_this->object_lock );
531 #if defined( PTH_INIT_IN_PTH_H )
532 p_this->thread_id = pth_spawn( PTH_ATTR_DEFAULT, func, p_data );
533 i_ret = p_this->thread_id == NULL;
535 #elif defined( ST_INIT_IN_ST_H )
536 p_this->thread_id = st_thread_create( func, p_data, 1, 0 );
539 #elif defined( WIN32 ) || defined( UNDER_CE )
542 /* When using the MSVCRT C library you have to use the _beginthreadex
543 * function instead of CreateThread, otherwise you'll end up with
544 * memory leaks and the signal functions not working (see Microsoft
545 * Knowledge Base, article 104641) */
547 #if defined( UNDER_CE )
548 (HANDLE)CreateThread( NULL, 0, (PTHREAD_START) func,
549 p_data, 0, &threadID );
551 (HANDLE)_beginthreadex( NULL, 0, (PTHREAD_START) func,
552 p_data, 0, &threadID );
556 if( p_this->thread_id && i_priority )
558 if( !SetThreadPriority(p_this->thread_id, i_priority) )
560 msg_Warn( p_this, "couldn't set a faster priority" );
565 i_ret = ( p_this->thread_id ? 0 : 1 );
567 #elif defined( HAVE_KERNEL_SCHEDULER_H )
568 p_this->thread_id = spawn_thread( (thread_func)func, psz_name,
569 i_priority, p_data );
570 i_ret = resume_thread( p_this->thread_id );
572 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
573 i_ret = pthread_create( &p_this->thread_id, NULL, func, p_data );
576 if( config_GetInt( p_this, "rt-priority" ) )
579 int i_error, i_policy;
580 struct sched_param param;
582 memset( ¶m, 0, sizeof(struct sched_param) );
583 if( config_GetType( p_this, "rt-offset" ) )
585 i_priority += config_GetInt( p_this, "rt-offset" );
587 if( i_priority <= 0 )
589 param.sched_priority = (-1) * i_priority;
590 i_policy = SCHED_OTHER;
594 param.sched_priority = i_priority;
597 if( (i_error = pthread_setschedparam( p_this->thread_id,
598 i_policy, ¶m )) )
600 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %s",
601 psz_file, i_line, strerror(i_error) );
612 #elif defined( HAVE_CTHREADS_H )
613 p_this->thread_id = cthread_fork( (cthread_fn_t)func, (any_t)p_data );
622 msg_Dbg( p_this, "waiting for thread completion" );
623 vlc_cond_wait( &p_this->object_wait, &p_this->object_lock );
626 p_this->b_thread = 1;
628 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
629 (unsigned int)p_this->thread_id, psz_name, i_priority,
632 vlc_mutex_unlock( &p_this->object_lock );
636 msg_Err( p_this, "%s thread could not be created at %s:%d (%s)",
637 psz_name, psz_file, i_line, strerror(i_ret) );
638 vlc_mutex_unlock( &p_this->object_lock );
644 /*****************************************************************************
645 * vlc_thread_set_priority: set the priority of the current thread when we
646 * couldn't set it in vlc_thread_create (for instance for the main thread)
647 *****************************************************************************/
648 int __vlc_thread_set_priority( vlc_object_t *p_this, char * psz_file,
649 int i_line, int i_priority )
651 #if defined( PTH_INIT_IN_PTH_H ) || defined( ST_INIT_IN_ST_H )
652 #elif defined( WIN32 ) || defined( UNDER_CE )
653 if( !SetThreadPriority(GetCurrentThread(), i_priority) )
655 msg_Warn( p_this, "couldn't set a faster priority" );
659 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
661 if( config_GetInt( p_this, "rt-priority" ) )
664 int i_error, i_policy;
665 struct sched_param param;
667 memset( ¶m, 0, sizeof(struct sched_param) );
668 if( config_GetType( p_this, "rt-offset" ) )
670 i_priority += config_GetInt( p_this, "rt-offset" );
672 if( i_priority <= 0 )
674 param.sched_priority = (-1) * i_priority;
675 i_policy = SCHED_OTHER;
679 param.sched_priority = i_priority;
682 if( !p_this->thread_id )
683 p_this->thread_id = pthread_self();
684 if( (i_error = pthread_setschedparam( p_this->thread_id,
685 i_policy, ¶m )) )
687 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %s",
688 psz_file, i_line, strerror(i_error) );
697 /*****************************************************************************
698 * vlc_thread_ready: tell the parent thread we were successfully spawned
699 *****************************************************************************/
700 void __vlc_thread_ready( vlc_object_t *p_this )
702 vlc_mutex_lock( &p_this->object_lock );
703 vlc_cond_signal( &p_this->object_wait );
704 vlc_mutex_unlock( &p_this->object_lock );
707 /*****************************************************************************
708 * vlc_thread_join: wait until a thread exits, inner version
709 *****************************************************************************/
710 void __vlc_thread_join( vlc_object_t *p_this, char * psz_file, int i_line )
714 #if defined( PTH_INIT_IN_PTH_H )
715 i_ret = ( pth_join( p_this->thread_id, NULL ) == FALSE );
717 #elif defined( ST_INIT_IN_ST_H )
718 i_ret = st_thread_join( p_this->thread_id, NULL );
720 #elif defined( UNDER_CE ) || defined( WIN32 )
722 BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
723 FILETIME*, FILETIME* );
724 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
725 int64_t real_time, kernel_time, user_time;
727 WaitForSingleObject( p_this->thread_id, INFINITE );
729 #if defined( UNDER_CE )
730 hmodule = GetModuleHandle( _T("COREDLL") );
732 hmodule = GetModuleHandle( _T("KERNEL32") );
734 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
735 FILETIME*, FILETIME* ))
736 GetProcAddress( hmodule, _T("GetThreadTimes") );
738 if( OurGetThreadTimes &&
739 OurGetThreadTimes( p_this->thread_id,
740 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
743 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
744 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
748 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
749 kernel_ft.dwLowDateTime) / 10;
752 ((((int64_t)user_ft.dwHighDateTime)<<32)|
753 user_ft.dwLowDateTime) / 10;
755 msg_Dbg( p_this, "thread times: "
756 "real "I64Fd"m%fs, kernel "I64Fd"m%fs, user "I64Fd"m%fs",
757 real_time/60/1000000,
758 (double)((real_time%(60*1000000))/1000000.0),
759 kernel_time/60/1000000,
760 (double)((kernel_time%(60*1000000))/1000000.0),
761 user_time/60/1000000,
762 (double)((user_time%(60*1000000))/1000000.0) );
764 CloseHandle( p_this->thread_id );
766 #elif defined( HAVE_KERNEL_SCHEDULER_H )
768 wait_for_thread( p_this->thread_id, &exit_value );
770 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
771 i_ret = pthread_join( p_this->thread_id, NULL );
773 #elif defined( HAVE_CTHREADS_H )
774 cthread_join( p_this->thread_id );
781 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%s)",
782 (unsigned int)p_this->thread_id, psz_file, i_line,
787 msg_Dbg( p_this, "thread %u joined (%s:%d)",
788 (unsigned int)p_this->thread_id, psz_file, i_line );
791 p_this->b_thread = 0;