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( UNDER_CE )
50 #elif defined( WIN32 )
51 #elif defined( HAVE_KERNEL_SCHEDULER_H )
52 #elif defined( LIBVLC_USE_PTHREAD )
53 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
57 * Global process-wide VLC object.
58 * Contains inter-instance data, such as the module cache and global mutexes.
60 static libvlc_global_data_t *p_root;
62 libvlc_global_data_t *vlc_global( void )
64 assert( i_initializations > 0 );
69 vlc_threadvar_t msg_context_global_key;
71 #if defined(LIBVLC_USE_PTHREAD)
72 static inline unsigned long vlc_threadid (void)
74 union { pthread_t th; unsigned long int i; } v = { };
75 v.th = pthread_self ();
80 /*****************************************************************************
81 * vlc_thread_fatal: Report an error from the threading layer
82 *****************************************************************************
83 * This is mostly meant for debugging.
84 *****************************************************************************/
85 void vlc_pthread_fatal (const char *action, int error,
86 const char *file, unsigned line)
88 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
89 action, vlc_threadid (), file, line, error);
92 /* Sometimes strerror_r() crashes too, so make sure we print an error
93 * message before we invoke it */
95 /* Avoid the strerror_r() prototype brain damage in glibc */
97 fprintf (stderr, " Error message: %m\n");
102 switch (strerror_r (error, buf, sizeof (buf)))
107 case ERANGE: /* should never happen */
108 msg = "unknwon (too big to display)";
111 msg = "unknown (invalid error number)";
114 fprintf (stderr, " Error message: %s\n", msg);
123 /*****************************************************************************
124 * vlc_threads_init: initialize threads system
125 *****************************************************************************
126 * This function requires lazy initialization of a global lock in order to
127 * keep the library really thread-safe. Some architectures don't support this
128 * and thus do not guarantee the complete reentrancy.
129 *****************************************************************************/
130 int vlc_threads_init( void )
132 int i_ret = VLC_SUCCESS;
134 /* If we have lazy mutex initialization, use it. Otherwise, we just
135 * hope nothing wrong happens. */
136 #if defined( UNDER_CE )
137 #elif defined( WIN32 )
138 #elif defined( HAVE_KERNEL_SCHEDULER_H )
139 #elif defined( LIBVLC_USE_PTHREAD )
140 pthread_mutex_lock( &once_mutex );
143 if( i_initializations == 0 )
145 p_root = vlc_custom_create( NULL, sizeof( *p_root ),
146 VLC_OBJECT_GENERIC, "root" );
153 /* We should be safe now. Do all the initialization stuff we want. */
154 vlc_threadvar_create( p_root, &msg_context_global_key );
159 /* If we have lazy mutex initialization support, unlock the mutex.
160 * Otherwize, we are screwed. */
161 #if defined( UNDER_CE )
162 #elif defined( WIN32 )
163 #elif defined( HAVE_KERNEL_SCHEDULER_H )
164 #elif defined( LIBVLC_USE_PTHREAD )
165 pthread_mutex_unlock( &once_mutex );
171 /*****************************************************************************
172 * vlc_threads_end: stop threads system
173 *****************************************************************************
174 * FIXME: This function is far from being threadsafe.
175 *****************************************************************************/
176 void vlc_threads_end( void )
178 #if defined( UNDER_CE )
179 #elif defined( WIN32 )
180 #elif defined( HAVE_KERNEL_SCHEDULER_H )
181 #elif defined( LIBVLC_USE_PTHREAD )
182 pthread_mutex_lock( &once_mutex );
185 assert( i_initializations > 0 );
187 if( i_initializations == 1 )
188 vlc_object_release( p_root );
191 #if defined( UNDER_CE )
192 #elif defined( WIN32 )
193 #elif defined( HAVE_KERNEL_SCHEDULER_H )
194 #elif defined( LIBVLC_USE_PTHREAD )
195 pthread_mutex_unlock( &once_mutex );
200 /* This is not prototyped under Linux, though it exists. */
201 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
204 /*****************************************************************************
205 * vlc_mutex_init: initialize a mutex
206 *****************************************************************************/
207 int vlc_mutex_init( vlc_mutex_t *p_mutex )
209 #if defined( UNDER_CE )
210 InitializeCriticalSection( &p_mutex->csection );
213 #elif defined( WIN32 )
214 *p_mutex = CreateMutex( 0, FALSE, 0 );
215 return (*p_mutex != NULL) ? 0 : ENOMEM;
217 #elif defined( HAVE_KERNEL_SCHEDULER_H )
218 /* check the arguments and whether it's already been initialized */
219 if( p_mutex == NULL )
224 if( p_mutex->init == 9999 )
229 p_mutex->lock = create_sem( 1, "BeMutex" );
230 if( p_mutex->lock < B_NO_ERROR )
235 p_mutex->init = 9999;
238 #elif defined( LIBVLC_USE_PTHREAD )
239 pthread_mutexattr_t attr;
242 pthread_mutexattr_init( &attr );
245 /* Create error-checking mutex to detect problems more easily. */
246 # if defined(SYS_LINUX)
247 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
249 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
252 i_result = pthread_mutex_init( p_mutex, &attr );
253 pthread_mutexattr_destroy( &attr );
258 /*****************************************************************************
259 * vlc_mutex_init: initialize a recursive mutex (Do not use)
260 *****************************************************************************/
261 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
264 /* Create mutex returns a recursive mutex */
265 *p_mutex = CreateMutex( 0, FALSE, 0 );
266 return (*p_mutex != NULL) ? 0 : ENOMEM;
267 #elif defined( LIBVLC_USE_PTHREAD )
268 pthread_mutexattr_t attr;
271 pthread_mutexattr_init( &attr );
272 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
273 i_result = pthread_mutex_init( p_mutex, &attr );
274 pthread_mutexattr_destroy( &attr );
277 # error Unimplemented!
282 /*****************************************************************************
283 * vlc_mutex_destroy: destroy a mutex, inner version
284 *****************************************************************************/
285 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
287 #if defined( UNDER_CE )
288 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
290 DeleteCriticalSection( &p_mutex->csection );
292 #elif defined( WIN32 )
293 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
295 CloseHandle( *p_mutex );
297 #elif defined( HAVE_KERNEL_SCHEDULER_H )
298 if( p_mutex->init == 9999 )
299 delete_sem( p_mutex->lock );
303 #elif defined( LIBVLC_USE_PTHREAD )
304 int val = pthread_mutex_destroy( p_mutex );
305 VLC_THREAD_ASSERT ("destroying mutex");
310 /*****************************************************************************
311 * vlc_cond_init: initialize a condition
312 *****************************************************************************/
313 int __vlc_cond_init( vlc_cond_t *p_condvar )
315 #if defined( UNDER_CE ) || defined( WIN32 )
316 /* Initialize counter */
317 p_condvar->i_waiting_threads = 0;
319 /* Create an auto-reset event. */
320 p_condvar->event = CreateEvent( NULL, /* no security */
321 FALSE, /* auto-reset event */
322 FALSE, /* start non-signaled */
323 NULL ); /* unnamed */
324 return !p_condvar->event;
326 #elif defined( HAVE_KERNEL_SCHEDULER_H )
332 if( p_condvar->init == 9999 )
337 p_condvar->thread = -1;
338 p_condvar->init = 9999;
341 #elif defined( LIBVLC_USE_PTHREAD )
342 pthread_condattr_t attr;
345 ret = pthread_condattr_init (&attr);
349 # if !defined (_POSIX_CLOCK_SELECTION)
350 /* Fairly outdated POSIX support (that was defined in 2001) */
351 # define _POSIX_CLOCK_SELECTION (-1)
353 # if (_POSIX_CLOCK_SELECTION >= 0)
354 /* NOTE: This must be the same clock as the one in mtime.c */
355 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
358 ret = pthread_cond_init (p_condvar, &attr);
359 pthread_condattr_destroy (&attr);
365 /*****************************************************************************
366 * vlc_cond_destroy: destroy a condition, inner version
367 *****************************************************************************/
368 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
370 #if defined( UNDER_CE ) || defined( WIN32 )
371 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
373 CloseHandle( p_condvar->event );
375 #elif defined( HAVE_KERNEL_SCHEDULER_H )
378 #elif defined( LIBVLC_USE_PTHREAD )
379 int val = pthread_cond_destroy( p_condvar );
380 VLC_THREAD_ASSERT ("destroying condition");
385 /*****************************************************************************
386 * vlc_tls_create: create a thread-local variable
387 *****************************************************************************/
388 int __vlc_threadvar_create( vlc_threadvar_t *p_tls )
392 #if defined( HAVE_KERNEL_SCHEDULER_H )
393 # error Unimplemented!
394 #elif defined( UNDER_CE )
395 #elif defined( WIN32 )
397 i_ret = (*p_tls == INVALID_HANDLE_VALUE) ? EAGAIN : 0;
399 #elif defined( LIBVLC_USE_PTHREAD )
400 i_ret = pthread_key_create( p_tls, NULL );
405 /*****************************************************************************
406 * vlc_thread_create: create a thread, inner version
407 *****************************************************************************
408 * Note that i_priority is only taken into account on platforms supporting
409 * userland real-time priority threads.
410 *****************************************************************************/
411 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
412 const char *psz_name, void * ( *func ) ( void * ),
413 int i_priority, bool b_wait )
416 void *p_data = (void *)p_this;
417 vlc_object_internals_t *p_priv = vlc_internals( p_this );
419 vlc_mutex_lock( &p_this->object_lock );
421 #if defined( WIN32 ) || defined( UNDER_CE )
423 /* When using the MSVCRT C library you have to use the _beginthreadex
424 * function instead of CreateThread, otherwise you'll end up with
425 * memory leaks and the signal functions not working (see Microsoft
426 * Knowledge Base, article 104641) */
427 #if defined( UNDER_CE )
429 HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
430 (LPVOID)p_data, CREATE_SUSPENDED,
434 uintptr_t hThread = _beginthreadex( NULL, 0,
435 (LPTHREAD_START_ROUTINE)func,
436 (void*)p_data, CREATE_SUSPENDED,
439 p_priv->thread_id.id = (DWORD)threadId;
440 p_priv->thread_id.hThread = (HANDLE)hThread;
441 ResumeThread((HANDLE)hThread);
444 i_ret = ( p_priv->thread_id.hThread ? 0 : 1 );
446 if( !i_ret && i_priority )
448 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
450 msg_Warn( p_this, "couldn't set a faster priority" );
455 #elif defined( HAVE_KERNEL_SCHEDULER_H )
456 p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
457 i_priority, p_data );
458 i_ret = resume_thread( p_priv->thread_id );
460 #elif defined( LIBVLC_USE_PTHREAD )
461 i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
464 if( config_GetInt( p_this, "rt-priority" ) )
467 int i_error, i_policy;
468 struct sched_param param;
470 memset( ¶m, 0, sizeof(struct sched_param) );
471 if( config_GetType( p_this, "rt-offset" ) )
473 i_priority += config_GetInt( p_this, "rt-offset" );
475 if( i_priority <= 0 )
477 param.sched_priority = (-1) * i_priority;
478 i_policy = SCHED_OTHER;
482 param.sched_priority = i_priority;
485 if( (i_error = pthread_setschedparam( p_priv->thread_id,
486 i_policy, ¶m )) )
489 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
507 msg_Dbg( p_this, "waiting for thread completion" );
508 vlc_object_wait( p_this );
511 p_priv->b_thread = true;
513 #if defined( WIN32 ) || defined( UNDER_CE )
514 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
515 (unsigned int)p_priv->thread_id.id, psz_name,
516 i_priority, psz_file, i_line );
518 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
519 (unsigned int)p_priv->thread_id, psz_name, i_priority,
524 vlc_mutex_unlock( &p_this->object_lock );
529 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
530 psz_name, psz_file, i_line );
531 vlc_mutex_unlock( &p_this->object_lock );
537 /*****************************************************************************
538 * vlc_thread_set_priority: set the priority of the current thread when we
539 * couldn't set it in vlc_thread_create (for instance for the main thread)
540 *****************************************************************************/
541 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
542 int i_line, int i_priority )
544 vlc_object_internals_t *p_priv = vlc_internals( p_this );
545 #if defined( WIN32 ) || defined( UNDER_CE )
546 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
548 if( !p_priv->thread_id.hThread )
549 p_priv->thread_id.hThread = GetCurrentThread();
550 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
552 msg_Warn( p_this, "couldn't set a faster priority" );
556 #elif defined( LIBVLC_USE_PTHREAD )
558 if( config_GetInt( p_this, "rt-priority" ) > 0 )
561 int i_error, i_policy;
562 struct sched_param param;
564 memset( ¶m, 0, sizeof(struct sched_param) );
565 if( config_GetType( p_this, "rt-offset" ) )
567 i_priority += config_GetInt( p_this, "rt-offset" );
569 if( i_priority <= 0 )
571 param.sched_priority = (-1) * i_priority;
572 i_policy = SCHED_OTHER;
576 param.sched_priority = i_priority;
579 if( !p_priv->thread_id )
580 p_priv->thread_id = pthread_self();
581 if( (i_error = pthread_setschedparam( p_priv->thread_id,
582 i_policy, ¶m )) )
585 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
595 /*****************************************************************************
596 * vlc_thread_ready: tell the parent thread we were successfully spawned
597 *****************************************************************************/
598 void __vlc_thread_ready( vlc_object_t *p_this )
600 vlc_object_signal( p_this );
603 /*****************************************************************************
604 * vlc_thread_join: wait until a thread exits, inner version
605 *****************************************************************************/
606 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
608 vlc_object_internals_t *p_priv = vlc_internals( p_this );
610 #if 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(),
623 p_priv->thread_id.hThread,
628 DUPLICATE_SAME_ACCESS) )
630 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%u)",
631 (unsigned int)p_priv->thread_id.id,
632 psz_file, i_line, (unsigned int)GetLastError() );
633 p_priv->b_thread = false;
637 WaitForSingleObject( hThread, INFINITE );
639 msg_Dbg( p_this, "thread %u joined (%s:%d)",
640 (unsigned int)p_priv->thread_id.id,
642 #if defined( UNDER_CE )
643 hmodule = GetModuleHandle( _T("COREDLL") );
645 hmodule = GetModuleHandle( _T("KERNEL32") );
647 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
648 FILETIME*, FILETIME* ))
649 GetProcAddress( hmodule, _T("GetThreadTimes") );
651 if( OurGetThreadTimes &&
652 OurGetThreadTimes( hThread,
653 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
656 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
657 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
661 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
662 kernel_ft.dwLowDateTime) / 10;
665 ((((int64_t)user_ft.dwHighDateTime)<<32)|
666 user_ft.dwLowDateTime) / 10;
668 msg_Dbg( p_this, "thread times: "
669 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
670 real_time/60/1000000,
671 (double)((real_time%(60*1000000))/1000000.0),
672 kernel_time/60/1000000,
673 (double)((kernel_time%(60*1000000))/1000000.0),
674 user_time/60/1000000,
675 (double)((user_time%(60*1000000))/1000000.0) );
677 CloseHandle( hThread );
679 #else /* !defined(WIN32) */
683 #if defined( HAVE_KERNEL_SCHEDULER_H )
685 i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
687 #elif defined( LIBVLC_USE_PTHREAD )
688 /* Make sure we do return if we are calling vlc_thread_join()
689 * from the joined thread */
690 if (pthread_equal (pthread_self (), p_priv->thread_id))
691 i_ret = pthread_detach (p_priv->thread_id);
693 i_ret = pthread_join (p_priv->thread_id, NULL);
699 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%m)",
700 (unsigned int)p_priv->thread_id, psz_file, i_line );
704 msg_Dbg( p_this, "thread %u joined (%s:%d)",
705 (unsigned int)p_priv->thread_id, psz_file, i_line );
710 p_priv->b_thread = false;