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( p_root, &msg_context_global_key );
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 )
176 vlc_object_release( p_root );
179 #if defined( LIBVLC_USE_PTHREAD )
180 pthread_mutex_unlock( &once_mutex );
185 /* This is not prototyped under Linux, though it exists. */
186 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
189 /*****************************************************************************
190 * vlc_mutex_init: initialize a mutex
191 *****************************************************************************/
192 int vlc_mutex_init( vlc_mutex_t *p_mutex )
194 #if defined( LIBVLC_USE_PTHREAD )
195 pthread_mutexattr_t attr;
198 pthread_mutexattr_init( &attr );
201 /* Create error-checking mutex to detect problems more easily. */
202 # if defined(SYS_LINUX)
203 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
205 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
208 i_result = pthread_mutex_init( p_mutex, &attr );
209 pthread_mutexattr_destroy( &attr );
211 #elif defined( UNDER_CE )
212 InitializeCriticalSection( &p_mutex->csection );
215 #elif defined( WIN32 )
216 *p_mutex = CreateMutex( 0, FALSE, 0 );
217 return (*p_mutex != NULL) ? 0 : ENOMEM;
219 #elif defined( HAVE_KERNEL_SCHEDULER_H )
220 /* check the arguments and whether it's already been initialized */
221 if( p_mutex == NULL )
226 if( p_mutex->init == 9999 )
231 p_mutex->lock = create_sem( 1, "BeMutex" );
232 if( p_mutex->lock < B_NO_ERROR )
237 p_mutex->init = 9999;
243 /*****************************************************************************
244 * vlc_mutex_init: initialize a recursive mutex (Do not use)
245 *****************************************************************************/
246 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
248 #if defined( LIBVLC_USE_PTHREAD )
249 pthread_mutexattr_t attr;
252 pthread_mutexattr_init( &attr );
253 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
254 i_result = pthread_mutex_init( p_mutex, &attr );
255 pthread_mutexattr_destroy( &attr );
257 #elif defined( WIN32 )
258 /* Create mutex returns a recursive mutex */
259 *p_mutex = CreateMutex( 0, FALSE, 0 );
260 return (*p_mutex != NULL) ? 0 : ENOMEM;
262 # error Unimplemented!
267 /*****************************************************************************
268 * vlc_mutex_destroy: destroy a mutex, inner version
269 *****************************************************************************/
270 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
272 #if defined( LIBVLC_USE_PTHREAD )
273 int val = pthread_mutex_destroy( p_mutex );
274 VLC_THREAD_ASSERT ("destroying mutex");
276 #elif defined( UNDER_CE )
277 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
279 DeleteCriticalSection( &p_mutex->csection );
281 #elif defined( WIN32 )
282 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
284 CloseHandle( *p_mutex );
286 #elif defined( HAVE_KERNEL_SCHEDULER_H )
287 if( p_mutex->init == 9999 )
288 delete_sem( p_mutex->lock );
295 /*****************************************************************************
296 * vlc_cond_init: initialize a condition
297 *****************************************************************************/
298 int __vlc_cond_init( vlc_cond_t *p_condvar )
300 #if defined( LIBVLC_USE_PTHREAD )
301 pthread_condattr_t attr;
304 ret = pthread_condattr_init (&attr);
308 # if !defined (_POSIX_CLOCK_SELECTION)
309 /* Fairly outdated POSIX support (that was defined in 2001) */
310 # define _POSIX_CLOCK_SELECTION (-1)
312 # if (_POSIX_CLOCK_SELECTION >= 0)
313 /* NOTE: This must be the same clock as the one in mtime.c */
314 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
317 ret = pthread_cond_init (p_condvar, &attr);
318 pthread_condattr_destroy (&attr);
321 #elif defined( UNDER_CE ) || defined( WIN32 )
322 /* Initialize counter */
323 p_condvar->i_waiting_threads = 0;
325 /* Create an auto-reset event. */
326 p_condvar->event = CreateEvent( NULL, /* no security */
327 FALSE, /* auto-reset event */
328 FALSE, /* start non-signaled */
329 NULL ); /* unnamed */
330 return !p_condvar->event;
332 #elif defined( HAVE_KERNEL_SCHEDULER_H )
338 if( p_condvar->init == 9999 )
343 p_condvar->thread = -1;
344 p_condvar->init = 9999;
350 /*****************************************************************************
351 * vlc_cond_destroy: destroy a condition, inner version
352 *****************************************************************************/
353 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
355 #if defined( LIBVLC_USE_PTHREAD )
356 int val = pthread_cond_destroy( p_condvar );
357 VLC_THREAD_ASSERT ("destroying condition");
359 #elif defined( UNDER_CE ) || defined( WIN32 )
360 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
362 CloseHandle( p_condvar->event );
364 #elif defined( HAVE_KERNEL_SCHEDULER_H )
370 /*****************************************************************************
371 * vlc_tls_create: create a thread-local variable
372 *****************************************************************************/
373 int __vlc_threadvar_create( vlc_threadvar_t *p_tls )
377 #if defined( LIBVLC_USE_PTHREAD )
378 i_ret = pthread_key_create( p_tls, NULL );
379 #elif defined( UNDER_CE )
380 #elif defined( WIN32 )
382 i_ret = (*p_tls == INVALID_HANDLE_VALUE) ? EAGAIN : 0;
384 # error Unimplemented!
389 /*****************************************************************************
390 * vlc_thread_create: create a thread, inner version
391 *****************************************************************************
392 * Note that i_priority is only taken into account on platforms supporting
393 * userland real-time priority threads.
394 *****************************************************************************/
395 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
396 const char *psz_name, void * ( *func ) ( void * ),
397 int i_priority, bool b_wait )
400 void *p_data = (void *)p_this;
401 vlc_object_internals_t *p_priv = vlc_internals( p_this );
403 vlc_mutex_lock( &p_this->object_lock );
405 #if defined( LIBVLC_USE_PTHREAD )
406 i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
409 if( config_GetInt( p_this, "rt-priority" ) > 0 )
412 int i_error, i_policy;
413 struct sched_param param;
415 memset( ¶m, 0, sizeof(struct sched_param) );
416 if( config_GetType( p_this, "rt-offset" ) )
417 i_priority += config_GetInt( p_this, "rt-offset" );
418 if( i_priority <= 0 )
420 param.sched_priority = (-1) * i_priority;
421 i_policy = SCHED_OTHER;
425 param.sched_priority = i_priority;
428 if( (i_error = pthread_setschedparam( p_priv->thread_id,
429 i_policy, ¶m )) )
432 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
442 #elif defined( WIN32 ) || defined( UNDER_CE )
444 /* When using the MSVCRT C library you have to use the _beginthreadex
445 * function instead of CreateThread, otherwise you'll end up with
446 * memory leaks and the signal functions not working (see Microsoft
447 * Knowledge Base, article 104641) */
448 #if defined( UNDER_CE )
450 HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
451 (LPVOID)p_data, CREATE_SUSPENDED,
455 uintptr_t hThread = _beginthreadex( NULL, 0,
456 (LPTHREAD_START_ROUTINE)func,
457 (void*)p_data, CREATE_SUSPENDED,
460 p_priv->thread_id.id = (DWORD)threadId;
461 p_priv->thread_id.hThread = (HANDLE)hThread;
462 ResumeThread((HANDLE)hThread);
465 i_ret = ( p_priv->thread_id.hThread ? 0 : 1 );
467 if( !i_ret && i_priority )
469 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
471 msg_Warn( p_this, "couldn't set a faster priority" );
476 #elif defined( HAVE_KERNEL_SCHEDULER_H )
477 p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
478 i_priority, p_data );
479 i_ret = resume_thread( p_priv->thread_id );
487 msg_Dbg( p_this, "waiting for thread completion" );
488 vlc_object_wait( p_this );
491 p_priv->b_thread = true;
493 #if defined( WIN32 ) || defined( UNDER_CE )
494 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
495 (unsigned int)p_priv->thread_id.id, psz_name, i_priority,
498 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
499 (unsigned int)p_priv->thread_id, psz_name, i_priority,
506 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
507 psz_name, psz_file, i_line );
510 vlc_mutex_unlock( &p_this->object_lock );
514 /*****************************************************************************
515 * vlc_thread_set_priority: set the priority of the current thread when we
516 * couldn't set it in vlc_thread_create (for instance for the main thread)
517 *****************************************************************************/
518 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
519 int i_line, int i_priority )
521 vlc_object_internals_t *p_priv = vlc_internals( p_this );
523 #if defined( LIBVLC_USE_PTHREAD )
525 if( config_GetInt( p_this, "rt-priority" ) > 0 )
528 int i_error, i_policy;
529 struct sched_param param;
531 memset( ¶m, 0, sizeof(struct sched_param) );
532 if( config_GetType( p_this, "rt-offset" ) )
533 i_priority += config_GetInt( p_this, "rt-offset" );
534 if( i_priority <= 0 )
536 param.sched_priority = (-1) * i_priority;
537 i_policy = SCHED_OTHER;
541 param.sched_priority = i_priority;
544 if( !p_priv->thread_id )
545 p_priv->thread_id = pthread_self();
546 if( (i_error = pthread_setschedparam( p_priv->thread_id,
547 i_policy, ¶m )) )
550 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
556 #elif defined( WIN32 ) || defined( UNDER_CE )
557 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
559 if( !p_priv->thread_id.hThread )
560 p_priv->thread_id.hThread = GetCurrentThread();
561 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
563 msg_Warn( p_this, "couldn't set a faster priority" );
572 /*****************************************************************************
573 * vlc_thread_ready: tell the parent thread we were successfully spawned
574 *****************************************************************************/
575 void __vlc_thread_ready( vlc_object_t *p_this )
577 vlc_object_signal( p_this );
580 /*****************************************************************************
581 * vlc_thread_join: wait until a thread exits, inner version
582 *****************************************************************************/
583 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
585 vlc_object_internals_t *p_priv = vlc_internals( p_this );
588 #if defined( LIBVLC_USE_PTHREAD )
589 /* Make sure we do return if we are calling vlc_thread_join()
590 * from the joined thread */
591 if (pthread_equal (pthread_self (), p_priv->thread_id))
592 i_ret = pthread_detach (p_priv->thread_id);
594 i_ret = pthread_join (p_priv->thread_id, NULL);
596 #elif defined( UNDER_CE ) || defined( WIN32 )
598 BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
599 FILETIME*, FILETIME* );
600 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
601 int64_t real_time, kernel_time, user_time;
605 ** object will close its thread handle when destroyed, duplicate it here
606 ** to be on the safe side
608 if( ! DuplicateHandle(GetCurrentProcess(),
609 p_priv->thread_id.hThread,
614 DUPLICATE_SAME_ACCESS) )
616 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%u)",
617 (unsigned int)p_priv->thread_id.id,
618 psz_file, i_line, (unsigned int)GetLastError() );
619 p_priv->b_thread = false;
623 WaitForSingleObject( hThread, INFINITE );
625 msg_Dbg( p_this, "thread %u joined (%s:%d)",
626 (unsigned int)p_priv->thread_id.id,
628 #if defined( UNDER_CE )
629 hmodule = GetModuleHandle( _T("COREDLL") );
631 hmodule = GetModuleHandle( _T("KERNEL32") );
633 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
634 FILETIME*, FILETIME* ))
635 GetProcAddress( hmodule, _T("GetThreadTimes") );
637 if( OurGetThreadTimes &&
638 OurGetThreadTimes( hThread,
639 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
642 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
643 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
647 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
648 kernel_ft.dwLowDateTime) / 10;
651 ((((int64_t)user_ft.dwHighDateTime)<<32)|
652 user_ft.dwLowDateTime) / 10;
654 msg_Dbg( p_this, "thread times: "
655 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
656 real_time/60/1000000,
657 (double)((real_time%(60*1000000))/1000000.0),
658 kernel_time/60/1000000,
659 (double)((kernel_time%(60*1000000))/1000000.0),
660 user_time/60/1000000,
661 (double)((user_time%(60*1000000))/1000000.0) );
663 CloseHandle( hThread );
665 #elif defined( HAVE_KERNEL_SCHEDULER_H )
667 i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
674 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%m)",
675 (unsigned int)p_priv->thread_id, psz_file, i_line );
678 msg_Dbg( p_this, "thread %u joined (%s:%d)",
679 (unsigned int)p_priv->thread_id, psz_file, i_line );
681 p_priv->b_thread = false;