1 /*****************************************************************************
2 * threads.c : threads implementation for the VideoLAN client
3 *****************************************************************************
4 * Copyright (C) 1999-2007 the VideoLAN team
7 * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
8 * Samuel Hocevar <sam@zoy.org>
9 * Gildas Bazin <gbazin@netcourrier.com>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
39 #define VLC_THREADS_UNINITIALIZED 0
40 #define VLC_THREADS_PENDING 1
41 #define VLC_THREADS_ERROR 2
42 #define VLC_THREADS_READY 3
44 /*****************************************************************************
45 * Global mutex for lazy initialization of the threads system
46 *****************************************************************************/
47 static volatile unsigned i_initializations = 0;
49 #if defined( LIBVLC_USE_PTHREAD )
50 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
54 * Global process-wide VLC object.
55 * Contains inter-instance data, such as the module cache and global mutexes.
57 static libvlc_global_data_t *p_root;
59 libvlc_global_data_t *vlc_global( void )
61 assert( i_initializations > 0 );
66 vlc_threadvar_t msg_context_global_key;
68 #if defined(LIBVLC_USE_PTHREAD)
69 static inline unsigned long vlc_threadid (void)
71 union { pthread_t th; unsigned long int i; } v = { };
72 v.th = pthread_self ();
76 /*****************************************************************************
77 * vlc_thread_fatal: Report an error from the threading layer
78 *****************************************************************************
79 * This is mostly meant for debugging.
80 *****************************************************************************/
81 void vlc_pthread_fatal (const char *action, int error,
82 const char *file, unsigned line)
84 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
85 action, vlc_threadid (), file, line, error);
88 /* Sometimes strerror_r() crashes too, so make sure we print an error
89 * message before we invoke it */
91 /* Avoid the strerror_r() prototype brain damage in glibc */
93 fprintf (stderr, " Error message: %m\n");
98 switch (strerror_r (error, buf, sizeof (buf)))
103 case ERANGE: /* should never happen */
104 msg = "unknwon (too big to display)";
107 msg = "unknown (invalid error number)";
110 fprintf (stderr, " Error message: %s\n", msg);
117 void vlc_pthread_fatal (const char *action, int error,
118 const char *file, unsigned line)
120 (void)action; (void)error; (void)file; (void)line;
125 /*****************************************************************************
126 * vlc_threads_init: initialize threads system
127 *****************************************************************************
128 * This function requires lazy initialization of a global lock in order to
129 * keep the library really thread-safe. Some architectures don't support this
130 * and thus do not guarantee the complete reentrancy.
131 *****************************************************************************/
132 int vlc_threads_init( void )
134 int i_ret = VLC_SUCCESS;
136 /* If we have lazy mutex initialization, use it. Otherwise, we just
137 * hope nothing wrong happens. */
138 #if defined( LIBVLC_USE_PTHREAD )
139 pthread_mutex_lock( &once_mutex );
142 if( i_initializations == 0 )
144 p_root = vlc_custom_create( NULL, sizeof( *p_root ),
145 VLC_OBJECT_GENERIC, "root" );
152 /* We should be safe now. Do all the initialization stuff we want. */
153 vlc_threadvar_create( &msg_context_global_key, msg_StackDestroy );
158 /* If we have lazy mutex initialization support, unlock the mutex.
159 * Otherwize, we are screwed. */
160 #if defined( LIBVLC_USE_PTHREAD )
161 pthread_mutex_unlock( &once_mutex );
167 /*****************************************************************************
168 * vlc_threads_end: stop threads system
169 *****************************************************************************
170 * FIXME: This function is far from being threadsafe.
171 *****************************************************************************/
172 void vlc_threads_end( void )
174 #if defined( LIBVLC_USE_PTHREAD )
175 pthread_mutex_lock( &once_mutex );
178 assert( i_initializations > 0 );
180 if( i_initializations == 1 )
182 vlc_object_release( p_root );
183 vlc_threadvar_delete( &msg_context_global_key );
187 #if defined( LIBVLC_USE_PTHREAD )
188 pthread_mutex_unlock( &once_mutex );
192 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
193 /* This is not prototyped under glibc, though it exists. */
194 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
197 /*****************************************************************************
198 * vlc_mutex_init: initialize a mutex
199 *****************************************************************************/
200 int vlc_mutex_init( vlc_mutex_t *p_mutex )
202 #if defined( LIBVLC_USE_PTHREAD )
203 pthread_mutexattr_t attr;
206 pthread_mutexattr_init( &attr );
209 /* Create error-checking mutex to detect problems more easily. */
210 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
211 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
213 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
216 i_result = pthread_mutex_init( p_mutex, &attr );
217 pthread_mutexattr_destroy( &attr );
219 #elif defined( UNDER_CE )
220 InitializeCriticalSection( &p_mutex->csection );
223 #elif defined( WIN32 )
224 *p_mutex = CreateMutex( 0, FALSE, 0 );
225 return (*p_mutex != NULL) ? 0 : ENOMEM;
227 #elif defined( HAVE_KERNEL_SCHEDULER_H )
228 /* check the arguments and whether it's already been initialized */
229 if( p_mutex == NULL )
234 if( p_mutex->init == 9999 )
239 p_mutex->lock = create_sem( 1, "BeMutex" );
240 if( p_mutex->lock < B_NO_ERROR )
245 p_mutex->init = 9999;
251 /*****************************************************************************
252 * vlc_mutex_init: initialize a recursive mutex (Do not use)
253 *****************************************************************************/
254 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
256 #if defined( LIBVLC_USE_PTHREAD )
257 pthread_mutexattr_t attr;
260 pthread_mutexattr_init( &attr );
261 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
262 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
264 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
266 i_result = pthread_mutex_init( p_mutex, &attr );
267 pthread_mutexattr_destroy( &attr );
269 #elif defined( WIN32 )
270 /* Create mutex returns a recursive mutex */
271 *p_mutex = CreateMutex( 0, FALSE, 0 );
272 return (*p_mutex != NULL) ? 0 : ENOMEM;
274 # error Unimplemented!
279 /*****************************************************************************
280 * vlc_mutex_destroy: destroy a mutex, inner version
281 *****************************************************************************/
282 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
284 #if defined( LIBVLC_USE_PTHREAD )
285 int val = pthread_mutex_destroy( p_mutex );
286 VLC_THREAD_ASSERT ("destroying mutex");
288 #elif defined( UNDER_CE )
289 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
291 DeleteCriticalSection( &p_mutex->csection );
293 #elif defined( WIN32 )
294 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
296 CloseHandle( *p_mutex );
298 #elif defined( HAVE_KERNEL_SCHEDULER_H )
299 if( p_mutex->init == 9999 )
300 delete_sem( p_mutex->lock );
307 /*****************************************************************************
308 * vlc_cond_init: initialize a condition
309 *****************************************************************************/
310 int __vlc_cond_init( vlc_cond_t *p_condvar )
312 #if defined( LIBVLC_USE_PTHREAD )
313 pthread_condattr_t attr;
316 ret = pthread_condattr_init (&attr);
320 # if !defined (_POSIX_CLOCK_SELECTION)
321 /* Fairly outdated POSIX support (that was defined in 2001) */
322 # define _POSIX_CLOCK_SELECTION (-1)
324 # if (_POSIX_CLOCK_SELECTION >= 0)
325 /* NOTE: This must be the same clock as the one in mtime.c */
326 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
329 ret = pthread_cond_init (p_condvar, &attr);
330 pthread_condattr_destroy (&attr);
333 #elif defined( UNDER_CE ) || defined( WIN32 )
334 /* Initialize counter */
335 p_condvar->i_waiting_threads = 0;
337 /* Create an auto-reset event. */
338 p_condvar->event = CreateEvent( NULL, /* no security */
339 FALSE, /* auto-reset event */
340 FALSE, /* start non-signaled */
341 NULL ); /* unnamed */
342 return !p_condvar->event;
344 #elif defined( HAVE_KERNEL_SCHEDULER_H )
350 if( p_condvar->init == 9999 )
355 p_condvar->thread = -1;
356 p_condvar->init = 9999;
362 /*****************************************************************************
363 * vlc_cond_destroy: destroy a condition, inner version
364 *****************************************************************************/
365 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
367 #if defined( LIBVLC_USE_PTHREAD )
368 int val = pthread_cond_destroy( p_condvar );
369 VLC_THREAD_ASSERT ("destroying condition");
371 #elif defined( UNDER_CE ) || defined( WIN32 )
372 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
374 CloseHandle( p_condvar->event );
376 #elif defined( HAVE_KERNEL_SCHEDULER_H )
382 /*****************************************************************************
383 * vlc_tls_create: create a thread-local variable
384 *****************************************************************************/
385 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
389 #if defined( LIBVLC_USE_PTHREAD )
390 i_ret = pthread_key_create( p_tls, destr );
391 #elif defined( UNDER_CE )
393 #elif defined( WIN32 )
395 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
397 # error Unimplemented!
402 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
404 #if defined( LIBVLC_USE_PTHREAD )
405 pthread_key_delete (*p_tls);
406 #elif defined( UNDER_CE )
407 #elif defined( WIN32 )
410 # error Unimplemented!
414 /*****************************************************************************
415 * vlc_thread_create: create a thread, inner version
416 *****************************************************************************
417 * Note that i_priority is only taken into account on platforms supporting
418 * userland real-time priority threads.
419 *****************************************************************************/
420 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
421 const char *psz_name, void * ( *func ) ( void * ),
422 int i_priority, bool b_wait )
425 void *p_data = (void *)p_this;
426 vlc_object_internals_t *p_priv = vlc_internals( p_this );
428 vlc_mutex_lock( &p_this->object_lock );
430 #if defined( LIBVLC_USE_PTHREAD )
431 i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
434 if( config_GetInt( p_this, "rt-priority" ) > 0 )
437 int i_error, i_policy;
438 struct sched_param param;
440 memset( ¶m, 0, sizeof(struct sched_param) );
441 if( config_GetType( p_this, "rt-offset" ) )
442 i_priority += config_GetInt( p_this, "rt-offset" );
443 if( i_priority <= 0 )
445 param.sched_priority = (-1) * i_priority;
446 i_policy = SCHED_OTHER;
450 param.sched_priority = i_priority;
453 if( (i_error = pthread_setschedparam( p_priv->thread_id,
454 i_policy, ¶m )) )
457 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
467 #elif defined( WIN32 ) || defined( UNDER_CE )
469 /* When using the MSVCRT C library you have to use the _beginthreadex
470 * function instead of CreateThread, otherwise you'll end up with
471 * memory leaks and the signal functions not working (see Microsoft
472 * Knowledge Base, article 104641) */
473 #if defined( UNDER_CE )
474 HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
475 (LPVOID)p_data, CREATE_SUSPENDED,
478 HANDLE hThread = (HANDLE)(uintptr_t)
479 _beginthreadex( NULL, 0, (LPTHREAD_START_ROUTINE)func,
480 (void *)p_data, CREATE_SUSPENDED, NULL );
482 p_priv->thread_id = hThread;
483 ResumeThread(hThread);
486 i_ret = ( p_priv->thread_id ? 0 : errno );
488 if( !i_ret && i_priority )
490 if( !SetThreadPriority(p_priv->thread_id, i_priority) )
492 msg_Warn( p_this, "couldn't set a faster priority" );
497 #elif defined( HAVE_KERNEL_SCHEDULER_H )
498 p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
499 i_priority, p_data );
500 i_ret = resume_thread( p_priv->thread_id );
508 msg_Dbg( p_this, "waiting for thread completion" );
509 vlc_object_wait( p_this );
512 p_priv->b_thread = true;
513 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
514 (unsigned long)p_priv->thread_id, psz_name, i_priority,
520 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
521 psz_name, psz_file, i_line );
524 vlc_mutex_unlock( &p_this->object_lock );
528 /*****************************************************************************
529 * vlc_thread_set_priority: set the priority of the current thread when we
530 * couldn't set it in vlc_thread_create (for instance for the main thread)
531 *****************************************************************************/
532 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
533 int i_line, int i_priority )
535 vlc_object_internals_t *p_priv = vlc_internals( p_this );
537 #if defined( LIBVLC_USE_PTHREAD )
539 if( config_GetInt( p_this, "rt-priority" ) > 0 )
542 int i_error, i_policy;
543 struct sched_param param;
545 memset( ¶m, 0, sizeof(struct sched_param) );
546 if( config_GetType( p_this, "rt-offset" ) )
547 i_priority += config_GetInt( p_this, "rt-offset" );
548 if( i_priority <= 0 )
550 param.sched_priority = (-1) * i_priority;
551 i_policy = SCHED_OTHER;
555 param.sched_priority = i_priority;
558 if( !p_priv->thread_id )
559 p_priv->thread_id = pthread_self();
560 if( (i_error = pthread_setschedparam( p_priv->thread_id,
561 i_policy, ¶m )) )
564 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
570 #elif defined( WIN32 ) || defined( UNDER_CE )
571 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
573 if( !p_priv->thread_id )
574 p_priv->thread_id = GetCurrentThread();
575 if( !SetThreadPriority(p_priv->thread_id, i_priority) )
577 msg_Warn( p_this, "couldn't set a faster priority" );
586 /*****************************************************************************
587 * vlc_thread_ready: tell the parent thread we were successfully spawned
588 *****************************************************************************/
589 void __vlc_thread_ready( vlc_object_t *p_this )
591 vlc_object_signal( p_this );
594 /*****************************************************************************
595 * vlc_thread_join: wait until a thread exits, inner version
596 *****************************************************************************/
597 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
599 vlc_object_internals_t *p_priv = vlc_internals( p_this );
602 #if defined( LIBVLC_USE_PTHREAD )
603 /* Make sure we do return if we are calling vlc_thread_join()
604 * from the joined thread */
605 if (pthread_equal (pthread_self (), p_priv->thread_id))
606 i_ret = pthread_detach (p_priv->thread_id);
608 i_ret = pthread_join (p_priv->thread_id, NULL);
610 #elif defined( UNDER_CE ) || defined( WIN32 )
612 BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
613 FILETIME*, FILETIME* );
614 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
615 int64_t real_time, kernel_time, user_time;
619 ** object will close its thread handle when destroyed, duplicate it here
620 ** to be on the safe side
622 if( ! DuplicateHandle(GetCurrentProcess(),
628 DUPLICATE_SAME_ACCESS) )
630 p_priv->b_thread = false;
631 i_ret = GetLastError();
635 WaitForSingleObject( hThread, INFINITE );
637 #if defined( UNDER_CE )
638 hmodule = GetModuleHandle( _T("COREDLL") );
640 hmodule = GetModuleHandle( _T("KERNEL32") );
642 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
643 FILETIME*, FILETIME* ))
644 GetProcAddress( hmodule, _T("GetThreadTimes") );
646 if( OurGetThreadTimes &&
647 OurGetThreadTimes( hThread,
648 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
651 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
652 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
656 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
657 kernel_ft.dwLowDateTime) / 10;
660 ((((int64_t)user_ft.dwHighDateTime)<<32)|
661 user_ft.dwLowDateTime) / 10;
663 msg_Dbg( p_this, "thread times: "
664 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
665 real_time/60/1000000,
666 (double)((real_time%(60*1000000))/1000000.0),
667 kernel_time/60/1000000,
668 (double)((kernel_time%(60*1000000))/1000000.0),
669 user_time/60/1000000,
670 (double)((user_time%(60*1000000))/1000000.0) );
672 CloseHandle( hThread );
675 #elif defined( HAVE_KERNEL_SCHEDULER_H )
677 i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
684 msg_Err( p_this, "thread_join(%lu) failed at %s:%d (%m)",
685 (unsigned long)p_priv->thread_id, psz_file, i_line );
688 msg_Dbg( p_this, "thread %lu joined (%s:%d)",
689 (unsigned long)p_priv->thread_id, psz_file, i_line );
691 p_priv->b_thread = false;