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 ();
77 /*****************************************************************************
78 * vlc_thread_fatal: Report an error from the threading layer
79 *****************************************************************************
80 * This is mostly meant for debugging.
81 *****************************************************************************/
82 void vlc_pthread_fatal (const char *action, int error,
83 const char *file, unsigned line)
85 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
86 action, vlc_threadid (), file, line, error);
89 /* Sometimes strerror_r() crashes too, so make sure we print an error
90 * message before we invoke it */
92 /* Avoid the strerror_r() prototype brain damage in glibc */
94 fprintf (stderr, " Error message: %m\n");
99 switch (strerror_r (error, buf, sizeof (buf)))
104 case ERANGE: /* should never happen */
105 msg = "unknwon (too big to display)";
108 msg = "unknown (invalid error number)";
111 fprintf (stderr, " Error message: %s\n", msg);
120 /*****************************************************************************
121 * vlc_threads_init: initialize threads system
122 *****************************************************************************
123 * This function requires lazy initialization of a global lock in order to
124 * keep the library really thread-safe. Some architectures don't support this
125 * and thus do not guarantee the complete reentrancy.
126 *****************************************************************************/
127 int vlc_threads_init( void )
129 int i_ret = VLC_SUCCESS;
131 /* If we have lazy mutex initialization, use it. Otherwise, we just
132 * hope nothing wrong happens. */
133 #if defined( LIBVLC_USE_PTHREAD )
134 pthread_mutex_lock( &once_mutex );
137 if( i_initializations == 0 )
139 p_root = vlc_custom_create( NULL, sizeof( *p_root ),
140 VLC_OBJECT_GENERIC, "root" );
147 /* We should be safe now. Do all the initialization stuff we want. */
148 vlc_threadvar_create( &msg_context_global_key, msg_StackDestroy );
153 /* If we have lazy mutex initialization support, unlock the mutex.
154 * Otherwize, we are screwed. */
155 #if defined( LIBVLC_USE_PTHREAD )
156 pthread_mutex_unlock( &once_mutex );
162 /*****************************************************************************
163 * vlc_threads_end: stop threads system
164 *****************************************************************************
165 * FIXME: This function is far from being threadsafe.
166 *****************************************************************************/
167 void vlc_threads_end( void )
169 #if defined( LIBVLC_USE_PTHREAD )
170 pthread_mutex_lock( &once_mutex );
173 assert( i_initializations > 0 );
175 if( i_initializations == 1 )
177 vlc_object_release( p_root );
178 vlc_threadvar_delete( &msg_context_global_key );
182 #if defined( LIBVLC_USE_PTHREAD )
183 pthread_mutex_unlock( &once_mutex );
187 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
188 /* This is not prototyped under glibc, though it exists. */
189 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
192 /*****************************************************************************
193 * vlc_mutex_init: initialize a mutex
194 *****************************************************************************/
195 int vlc_mutex_init( vlc_mutex_t *p_mutex )
197 #if defined( LIBVLC_USE_PTHREAD )
198 pthread_mutexattr_t attr;
201 pthread_mutexattr_init( &attr );
204 /* Create error-checking mutex to detect problems more easily. */
205 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
206 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
208 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
211 i_result = pthread_mutex_init( p_mutex, &attr );
212 pthread_mutexattr_destroy( &attr );
214 #elif defined( UNDER_CE )
215 InitializeCriticalSection( &p_mutex->csection );
218 #elif defined( WIN32 )
219 *p_mutex = CreateMutex( 0, FALSE, 0 );
220 return (*p_mutex != NULL) ? 0 : ENOMEM;
222 #elif defined( HAVE_KERNEL_SCHEDULER_H )
223 /* check the arguments and whether it's already been initialized */
224 if( p_mutex == NULL )
229 if( p_mutex->init == 9999 )
234 p_mutex->lock = create_sem( 1, "BeMutex" );
235 if( p_mutex->lock < B_NO_ERROR )
240 p_mutex->init = 9999;
246 /*****************************************************************************
247 * vlc_mutex_init: initialize a recursive mutex (Do not use)
248 *****************************************************************************/
249 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
251 #if defined( LIBVLC_USE_PTHREAD )
252 pthread_mutexattr_t attr;
255 pthread_mutexattr_init( &attr );
256 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
257 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
259 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
261 i_result = pthread_mutex_init( p_mutex, &attr );
262 pthread_mutexattr_destroy( &attr );
264 #elif defined( WIN32 )
265 /* Create mutex returns a recursive mutex */
266 *p_mutex = CreateMutex( 0, FALSE, 0 );
267 return (*p_mutex != NULL) ? 0 : ENOMEM;
269 # error Unimplemented!
274 /*****************************************************************************
275 * vlc_mutex_destroy: destroy a mutex, inner version
276 *****************************************************************************/
277 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
279 #if defined( LIBVLC_USE_PTHREAD )
280 int val = pthread_mutex_destroy( p_mutex );
281 VLC_THREAD_ASSERT ("destroying mutex");
283 #elif defined( UNDER_CE )
284 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
286 DeleteCriticalSection( &p_mutex->csection );
288 #elif defined( WIN32 )
289 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
291 CloseHandle( *p_mutex );
293 #elif defined( HAVE_KERNEL_SCHEDULER_H )
294 if( p_mutex->init == 9999 )
295 delete_sem( p_mutex->lock );
302 /*****************************************************************************
303 * vlc_cond_init: initialize a condition
304 *****************************************************************************/
305 int __vlc_cond_init( vlc_cond_t *p_condvar )
307 #if defined( LIBVLC_USE_PTHREAD )
308 pthread_condattr_t attr;
311 ret = pthread_condattr_init (&attr);
315 # if !defined (_POSIX_CLOCK_SELECTION)
316 /* Fairly outdated POSIX support (that was defined in 2001) */
317 # define _POSIX_CLOCK_SELECTION (-1)
319 # if (_POSIX_CLOCK_SELECTION >= 0)
320 /* NOTE: This must be the same clock as the one in mtime.c */
321 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
324 ret = pthread_cond_init (p_condvar, &attr);
325 pthread_condattr_destroy (&attr);
328 #elif defined( UNDER_CE ) || defined( WIN32 )
329 /* Initialize counter */
330 p_condvar->i_waiting_threads = 0;
332 /* Create an auto-reset event. */
333 p_condvar->event = CreateEvent( NULL, /* no security */
334 FALSE, /* auto-reset event */
335 FALSE, /* start non-signaled */
336 NULL ); /* unnamed */
337 return !p_condvar->event;
339 #elif defined( HAVE_KERNEL_SCHEDULER_H )
345 if( p_condvar->init == 9999 )
350 p_condvar->thread = -1;
351 p_condvar->init = 9999;
357 /*****************************************************************************
358 * vlc_cond_destroy: destroy a condition, inner version
359 *****************************************************************************/
360 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
362 #if defined( LIBVLC_USE_PTHREAD )
363 int val = pthread_cond_destroy( p_condvar );
364 VLC_THREAD_ASSERT ("destroying condition");
366 #elif defined( UNDER_CE ) || defined( WIN32 )
367 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
369 CloseHandle( p_condvar->event );
371 #elif defined( HAVE_KERNEL_SCHEDULER_H )
377 /*****************************************************************************
378 * vlc_tls_create: create a thread-local variable
379 *****************************************************************************/
380 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
384 #if defined( LIBVLC_USE_PTHREAD )
385 i_ret = pthread_key_create( p_tls, destr );
386 #elif defined( UNDER_CE )
388 #elif defined( WIN32 )
390 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
392 # error Unimplemented!
397 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
399 #if defined( LIBVLC_USE_PTHREAD )
400 pthread_key_delete (p_tls);
401 #elif defined( UNDER_CE )
402 #elif defined( WIN32 )
405 # error Unimplemented!
409 /*****************************************************************************
410 * vlc_thread_create: create a thread, inner version
411 *****************************************************************************
412 * Note that i_priority is only taken into account on platforms supporting
413 * userland real-time priority threads.
414 *****************************************************************************/
415 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
416 const char *psz_name, void * ( *func ) ( void * ),
417 int i_priority, bool b_wait )
420 void *p_data = (void *)p_this;
421 vlc_object_internals_t *p_priv = vlc_internals( p_this );
423 vlc_mutex_lock( &p_this->object_lock );
425 #if defined( LIBVLC_USE_PTHREAD )
426 i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
429 if( config_GetInt( p_this, "rt-priority" ) > 0 )
432 int i_error, i_policy;
433 struct sched_param param;
435 memset( ¶m, 0, sizeof(struct sched_param) );
436 if( config_GetType( p_this, "rt-offset" ) )
437 i_priority += config_GetInt( p_this, "rt-offset" );
438 if( i_priority <= 0 )
440 param.sched_priority = (-1) * i_priority;
441 i_policy = SCHED_OTHER;
445 param.sched_priority = i_priority;
448 if( (i_error = pthread_setschedparam( p_priv->thread_id,
449 i_policy, ¶m )) )
452 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
462 #elif defined( WIN32 ) || defined( UNDER_CE )
464 /* When using the MSVCRT C library you have to use the _beginthreadex
465 * function instead of CreateThread, otherwise you'll end up with
466 * memory leaks and the signal functions not working (see Microsoft
467 * Knowledge Base, article 104641) */
468 #if defined( UNDER_CE )
469 HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
470 (LPVOID)p_data, CREATE_SUSPENDED,
473 HANDLE hThread = (HANDLE)(uintptr_t)
474 _beginthreadex( NULL, 0, (LPTHREAD_START_ROUTINE)func,
475 (void *)p_data, CREATE_SUSPENDED, NULL );
477 p_priv->thread_id = hThread;
478 ResumeThread(hThread);
481 i_ret = ( p_priv->thread_id ? 0 : errno );
483 if( !i_ret && i_priority )
485 if( !SetThreadPriority(p_priv->thread_id, i_priority) )
487 msg_Warn( p_this, "couldn't set a faster priority" );
492 #elif defined( HAVE_KERNEL_SCHEDULER_H )
493 p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
494 i_priority, p_data );
495 i_ret = resume_thread( p_priv->thread_id );
503 msg_Dbg( p_this, "waiting for thread completion" );
504 vlc_object_wait( p_this );
507 p_priv->b_thread = true;
508 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
509 (unsigned long)p_priv->thread_id, psz_name, i_priority,
515 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
516 psz_name, psz_file, i_line );
519 vlc_mutex_unlock( &p_this->object_lock );
523 /*****************************************************************************
524 * vlc_thread_set_priority: set the priority of the current thread when we
525 * couldn't set it in vlc_thread_create (for instance for the main thread)
526 *****************************************************************************/
527 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
528 int i_line, int i_priority )
530 vlc_object_internals_t *p_priv = vlc_internals( p_this );
532 #if defined( LIBVLC_USE_PTHREAD )
534 if( config_GetInt( p_this, "rt-priority" ) > 0 )
537 int i_error, i_policy;
538 struct sched_param param;
540 memset( ¶m, 0, sizeof(struct sched_param) );
541 if( config_GetType( p_this, "rt-offset" ) )
542 i_priority += config_GetInt( p_this, "rt-offset" );
543 if( i_priority <= 0 )
545 param.sched_priority = (-1) * i_priority;
546 i_policy = SCHED_OTHER;
550 param.sched_priority = i_priority;
553 if( !p_priv->thread_id )
554 p_priv->thread_id = pthread_self();
555 if( (i_error = pthread_setschedparam( p_priv->thread_id,
556 i_policy, ¶m )) )
559 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
565 #elif defined( WIN32 ) || defined( UNDER_CE )
566 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
568 if( !p_priv->thread_id )
569 p_priv->thread_id = GetCurrentThread();
570 if( !SetThreadPriority(p_priv->thread_id, i_priority) )
572 msg_Warn( p_this, "couldn't set a faster priority" );
581 /*****************************************************************************
582 * vlc_thread_ready: tell the parent thread we were successfully spawned
583 *****************************************************************************/
584 void __vlc_thread_ready( vlc_object_t *p_this )
586 vlc_object_signal( p_this );
589 /*****************************************************************************
590 * vlc_thread_join: wait until a thread exits, inner version
591 *****************************************************************************/
592 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
594 vlc_object_internals_t *p_priv = vlc_internals( p_this );
597 #if defined( LIBVLC_USE_PTHREAD )
598 /* Make sure we do return if we are calling vlc_thread_join()
599 * from the joined thread */
600 if (pthread_equal (pthread_self (), p_priv->thread_id))
601 i_ret = pthread_detach (p_priv->thread_id);
603 i_ret = pthread_join (p_priv->thread_id, NULL);
605 #elif defined( UNDER_CE ) || defined( WIN32 )
607 BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
608 FILETIME*, FILETIME* );
609 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
610 int64_t real_time, kernel_time, user_time;
614 ** object will close its thread handle when destroyed, duplicate it here
615 ** to be on the safe side
617 if( ! DuplicateHandle(GetCurrentProcess(),
623 DUPLICATE_SAME_ACCESS) )
625 p_priv->b_thread = false;
626 i_ret = GetLastError();
630 WaitForSingleObject( hThread, INFINITE );
632 #if defined( UNDER_CE )
633 hmodule = GetModuleHandle( _T("COREDLL") );
635 hmodule = GetModuleHandle( _T("KERNEL32") );
637 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
638 FILETIME*, FILETIME* ))
639 GetProcAddress( hmodule, _T("GetThreadTimes") );
641 if( OurGetThreadTimes &&
642 OurGetThreadTimes( hThread,
643 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
646 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
647 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
651 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
652 kernel_ft.dwLowDateTime) / 10;
655 ((((int64_t)user_ft.dwHighDateTime)<<32)|
656 user_ft.dwLowDateTime) / 10;
658 msg_Dbg( p_this, "thread times: "
659 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
660 real_time/60/1000000,
661 (double)((real_time%(60*1000000))/1000000.0),
662 kernel_time/60/1000000,
663 (double)((kernel_time%(60*1000000))/1000000.0),
664 user_time/60/1000000,
665 (double)((user_time%(60*1000000))/1000000.0) );
667 CloseHandle( hThread );
670 #elif defined( HAVE_KERNEL_SCHEDULER_H )
672 i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
679 msg_Err( p_this, "thread_join(%lu) failed at %s:%d (%m)",
680 (unsigned long)p_priv->thread_id, psz_file, i_line );
683 msg_Dbg( p_this, "thread %lu joined (%s:%d)",
684 (unsigned long)p_priv->thread_id, psz_file, i_line );
686 p_priv->b_thread = false;