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;
48 static volatile int i_status = VLC_THREADS_UNINITIALIZED;
49 static vlc_object_t *p_root;
51 #if defined( UNDER_CE )
52 #elif defined( WIN32 )
53 #elif defined( HAVE_KERNEL_SCHEDULER_H )
54 #elif defined( LIBVLC_USE_PTHREAD )
55 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
58 vlc_threadvar_t msg_context_global_key;
60 #if defined(LIBVLC_USE_PTHREAD)
61 static inline unsigned long vlc_threadid (void)
63 union { pthread_t th; unsigned long int i; } v = { };
64 v.th = pthread_self ();
69 /*****************************************************************************
70 * vlc_thread_fatal: Report an error from the threading layer
71 *****************************************************************************
72 * This is mostly meant for debugging.
73 *****************************************************************************/
74 void vlc_pthread_fatal (const char *action, int error,
75 const char *file, unsigned line)
77 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
78 action, vlc_threadid (), file, line, error);
81 /* Sometimes strerror_r() crashes too, so make sure we print an error
82 * message before we invoke it */
84 /* Avoid the strerror_r() prototype brain damage in glibc */
86 fprintf (stderr, " Error message: %m\n");
91 switch (strerror_r (error, buf, sizeof (buf)))
96 case ERANGE: /* should never happen */
97 msg = "unknwon (too big to display)";
100 msg = "unknown (invalid error number)";
103 fprintf (stderr, " Error message: %s\n", msg);
112 /*****************************************************************************
113 * vlc_threads_init: initialize threads system
114 *****************************************************************************
115 * This function requires lazy initialization of a global lock in order to
116 * keep the library really thread-safe. Some architectures don't support this
117 * and thus do not guarantee the complete reentrancy.
118 *****************************************************************************/
119 int __vlc_threads_init( vlc_object_t *p_this )
121 libvlc_global_data_t *p_libvlc_global = (libvlc_global_data_t *)p_this;
122 int i_ret = VLC_SUCCESS;
124 /* If we have lazy mutex initialization, use it. Otherwise, we just
125 * hope nothing wrong happens. */
126 #if defined( UNDER_CE )
127 #elif defined( WIN32 )
128 #elif defined( HAVE_KERNEL_SCHEDULER_H )
129 #elif defined( LIBVLC_USE_PTHREAD )
130 pthread_mutex_lock( &once_mutex );
133 if( i_status == VLC_THREADS_UNINITIALIZED )
135 i_status = VLC_THREADS_PENDING;
137 /* We should be safe now. Do all the initialization stuff we want. */
138 p_libvlc_global->b_ready = false;
140 p_root = vlc_custom_create( VLC_OBJECT(p_libvlc_global), 0,
141 VLC_OBJECT_GLOBAL, "global" );
147 i_status = VLC_THREADS_ERROR;
152 i_status = VLC_THREADS_READY;
155 vlc_threadvar_create( p_root, &msg_context_global_key );
159 /* Just increment the initialization count */
163 /* If we have lazy mutex initialization support, unlock the mutex;
164 * otherwize, do a naive wait loop. */
165 #if defined( UNDER_CE )
166 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
167 #elif defined( WIN32 )
168 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
169 #elif defined( HAVE_KERNEL_SCHEDULER_H )
170 while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
171 #elif defined( LIBVLC_USE_PTHREAD )
172 pthread_mutex_unlock( &once_mutex );
175 if( i_status != VLC_THREADS_READY )
183 /*****************************************************************************
184 * vlc_threads_end: stop threads system
185 *****************************************************************************
186 * FIXME: This function is far from being threadsafe.
187 *****************************************************************************/
188 int __vlc_threads_end( vlc_object_t *p_this )
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_lock( &once_mutex );
198 if( i_initializations == 0 )
202 if( i_initializations == 0 )
204 i_status = VLC_THREADS_UNINITIALIZED;
205 vlc_object_release( p_root );
208 #if defined( UNDER_CE )
209 #elif defined( WIN32 )
210 #elif defined( HAVE_KERNEL_SCHEDULER_H )
211 #elif defined( LIBVLC_USE_PTHREAD )
212 pthread_mutex_unlock( &once_mutex );
218 /* This is not prototyped under Linux, though it exists. */
219 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
222 /*****************************************************************************
223 * vlc_mutex_init: initialize a mutex
224 *****************************************************************************/
225 int __vlc_mutex_init( vlc_mutex_t *p_mutex )
227 #if defined( UNDER_CE )
228 InitializeCriticalSection( &p_mutex->csection );
231 #elif defined( WIN32 )
232 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
233 return ( p_mutex->mutex != NULL ? 0 : 1 );
235 #elif defined( HAVE_KERNEL_SCHEDULER_H )
236 /* check the arguments and whether it's already been initialized */
237 if( p_mutex == NULL )
242 if( p_mutex->init == 9999 )
247 p_mutex->lock = create_sem( 1, "BeMutex" );
248 if( p_mutex->lock < B_NO_ERROR )
253 p_mutex->init = 9999;
256 #elif defined( LIBVLC_USE_PTHREAD )
257 pthread_mutexattr_t attr;
260 pthread_mutexattr_init( &attr );
263 /* Create error-checking mutex to detect problems more easily. */
264 # if defined(SYS_LINUX)
265 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
267 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
270 i_result = pthread_mutex_init( p_mutex, &attr );
271 pthread_mutexattr_destroy( &attr );
276 /*****************************************************************************
277 * vlc_mutex_init: initialize a recursive mutex (Do not use)
278 *****************************************************************************/
279 int __vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
282 /* Create mutex returns a recursive mutex */
283 p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
284 return ( p_mutex->mutex != NULL ? 0 : 1 );
285 #elif defined( LIBVLC_USE_PTHREAD )
286 pthread_mutexattr_t attr;
289 pthread_mutexattr_init( &attr );
291 /* Create error-checking mutex to detect problems more easily. */
292 # if defined(SYS_LINUX)
293 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
295 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
298 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
299 i_result = pthread_mutex_init( p_mutex, &attr );
300 pthread_mutexattr_destroy( &attr );
303 # error Unimplemented!
308 /*****************************************************************************
309 * vlc_mutex_destroy: destroy a mutex, inner version
310 *****************************************************************************/
311 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
313 #if defined( UNDER_CE )
314 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
316 DeleteCriticalSection( &p_mutex->csection );
318 #elif defined( WIN32 )
319 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
321 CloseHandle( p_mutex->mutex );
323 #elif defined( HAVE_KERNEL_SCHEDULER_H )
324 if( p_mutex->init == 9999 )
325 delete_sem( p_mutex->lock );
329 #elif defined( LIBVLC_USE_PTHREAD )
330 int val = pthread_mutex_destroy( p_mutex );
331 VLC_THREAD_ASSERT ("destroying mutex");
336 /*****************************************************************************
337 * vlc_cond_init: initialize a condition
338 *****************************************************************************/
339 int __vlc_cond_init( vlc_cond_t *p_condvar )
341 #if defined( UNDER_CE ) || defined( WIN32 )
342 /* Initialize counter */
343 p_condvar->i_waiting_threads = 0;
345 /* Create an auto-reset event. */
346 p_condvar->event = CreateEvent( NULL, /* no security */
347 FALSE, /* auto-reset event */
348 FALSE, /* start non-signaled */
349 NULL ); /* unnamed */
350 return !p_condvar->event;
352 #elif defined( HAVE_KERNEL_SCHEDULER_H )
358 if( p_condvar->init == 9999 )
363 p_condvar->thread = -1;
364 p_condvar->init = 9999;
367 #elif defined( LIBVLC_USE_PTHREAD )
368 pthread_condattr_t attr;
371 ret = pthread_condattr_init (&attr);
375 # if !defined (_POSIX_CLOCK_SELECTION)
376 /* Fairly outdated POSIX support (that was defined in 2001) */
377 # define _POSIX_CLOCK_SELECTION (-1)
379 # if (_POSIX_CLOCK_SELECTION >= 0)
380 /* NOTE: This must be the same clock as the one in mtime.c */
381 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
384 ret = pthread_cond_init (p_condvar, &attr);
385 pthread_condattr_destroy (&attr);
391 /*****************************************************************************
392 * vlc_cond_destroy: destroy a condition, inner version
393 *****************************************************************************/
394 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
396 #if defined( UNDER_CE ) || defined( WIN32 )
397 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
399 CloseHandle( p_condvar->event );
401 #elif defined( HAVE_KERNEL_SCHEDULER_H )
404 #elif defined( LIBVLC_USE_PTHREAD )
405 int val = pthread_cond_destroy( p_condvar );
406 VLC_THREAD_ASSERT ("destroying condition");
411 /*****************************************************************************
412 * vlc_tls_create: create a thread-local variable
413 *****************************************************************************/
414 int __vlc_threadvar_create( vlc_threadvar_t *p_tls )
418 #if defined( HAVE_KERNEL_SCHEDULER_H )
419 # error Unimplemented!
420 #elif defined( UNDER_CE ) || defined( WIN32 )
421 #elif defined( WIN32 )
423 i_ret = (*p_tls == INVALID_HANDLE_VALUE) ? EAGAIN : 0;
425 #elif defined( LIBVLC_USE_PTHREAD )
426 i_ret = pthread_key_create( p_tls, NULL );
431 /*****************************************************************************
432 * vlc_thread_create: create a thread, inner version
433 *****************************************************************************
434 * Note that i_priority is only taken into account on platforms supporting
435 * userland real-time priority threads.
436 *****************************************************************************/
437 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
438 const char *psz_name, void * ( *func ) ( void * ),
439 int i_priority, bool b_wait )
442 void *p_data = (void *)p_this;
443 vlc_object_internals_t *p_priv = p_this->p_internals;
445 vlc_mutex_lock( &p_this->object_lock );
447 #if defined( WIN32 ) || defined( UNDER_CE )
449 /* When using the MSVCRT C library you have to use the _beginthreadex
450 * function instead of CreateThread, otherwise you'll end up with
451 * memory leaks and the signal functions not working (see Microsoft
452 * Knowledge Base, article 104641) */
453 #if defined( UNDER_CE )
455 HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
456 (LPVOID)p_data, CREATE_SUSPENDED,
460 uintptr_t hThread = _beginthreadex( NULL, 0,
461 (LPTHREAD_START_ROUTINE)func,
462 (void*)p_data, CREATE_SUSPENDED,
465 p_priv->thread_id.id = (DWORD)threadId;
466 p_priv->thread_id.hThread = (HANDLE)hThread;
467 ResumeThread((HANDLE)hThread);
470 i_ret = ( p_priv->thread_id.hThread ? 0 : 1 );
472 if( !i_ret && i_priority )
474 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
476 msg_Warn( p_this, "couldn't set a faster priority" );
481 #elif defined( HAVE_KERNEL_SCHEDULER_H )
482 p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
483 i_priority, p_data );
484 i_ret = resume_thread( p_priv->thread_id );
486 #elif defined( LIBVLC_USE_PTHREAD )
487 i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
490 if( config_GetInt( p_this, "rt-priority" ) )
493 int i_error, i_policy;
494 struct sched_param param;
496 memset( ¶m, 0, sizeof(struct sched_param) );
497 if( config_GetType( p_this, "rt-offset" ) )
499 i_priority += config_GetInt( p_this, "rt-offset" );
501 if( i_priority <= 0 )
503 param.sched_priority = (-1) * i_priority;
504 i_policy = SCHED_OTHER;
508 param.sched_priority = i_priority;
511 if( (i_error = pthread_setschedparam( p_priv->thread_id,
512 i_policy, ¶m )) )
515 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
533 msg_Dbg( p_this, "waiting for thread completion" );
534 vlc_object_wait( p_this );
537 p_priv->b_thread = true;
539 #if defined( WIN32 ) || defined( UNDER_CE )
540 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
541 (unsigned int)p_priv->thread_id.id, psz_name,
542 i_priority, psz_file, i_line );
544 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
545 (unsigned int)p_priv->thread_id, psz_name, i_priority,
550 vlc_mutex_unlock( &p_this->object_lock );
555 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
556 psz_name, psz_file, i_line );
557 vlc_mutex_unlock( &p_this->object_lock );
563 /*****************************************************************************
564 * vlc_thread_set_priority: set the priority of the current thread when we
565 * couldn't set it in vlc_thread_create (for instance for the main thread)
566 *****************************************************************************/
567 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
568 int i_line, int i_priority )
570 vlc_object_internals_t *p_priv = p_this->p_internals;
571 #if defined( WIN32 ) || defined( UNDER_CE )
572 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
574 if( !p_priv->thread_id.hThread )
575 p_priv->thread_id.hThread = GetCurrentThread();
576 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
578 msg_Warn( p_this, "couldn't set a faster priority" );
582 #elif defined( LIBVLC_USE_PTHREAD )
584 if( config_GetInt( p_this, "rt-priority" ) > 0 )
587 int i_error, i_policy;
588 struct sched_param param;
590 memset( ¶m, 0, sizeof(struct sched_param) );
591 if( config_GetType( p_this, "rt-offset" ) )
593 i_priority += config_GetInt( p_this, "rt-offset" );
595 if( i_priority <= 0 )
597 param.sched_priority = (-1) * i_priority;
598 i_policy = SCHED_OTHER;
602 param.sched_priority = i_priority;
605 if( !p_priv->thread_id )
606 p_priv->thread_id = pthread_self();
607 if( (i_error = pthread_setschedparam( p_priv->thread_id,
608 i_policy, ¶m )) )
611 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
621 /*****************************************************************************
622 * vlc_thread_ready: tell the parent thread we were successfully spawned
623 *****************************************************************************/
624 void __vlc_thread_ready( vlc_object_t *p_this )
626 vlc_object_signal( p_this );
629 /*****************************************************************************
630 * vlc_thread_join: wait until a thread exits, inner version
631 *****************************************************************************/
632 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
634 vlc_object_internals_t *p_priv = p_this->p_internals;
636 #if defined( UNDER_CE ) || defined( WIN32 )
638 BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
639 FILETIME*, FILETIME* );
640 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
641 int64_t real_time, kernel_time, user_time;
645 ** object will close its thread handle when destroyed, duplicate it here
646 ** to be on the safe side
648 if( ! DuplicateHandle(GetCurrentProcess(),
649 p_priv->thread_id.hThread,
654 DUPLICATE_SAME_ACCESS) )
656 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%u)",
657 (unsigned int)p_priv->thread_id.id,
658 psz_file, i_line, (unsigned int)GetLastError() );
659 p_priv->b_thread = false;
663 WaitForSingleObject( hThread, INFINITE );
665 msg_Dbg( p_this, "thread %u joined (%s:%d)",
666 (unsigned int)p_priv->thread_id.id,
668 #if defined( UNDER_CE )
669 hmodule = GetModuleHandle( _T("COREDLL") );
671 hmodule = GetModuleHandle( _T("KERNEL32") );
673 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
674 FILETIME*, FILETIME* ))
675 GetProcAddress( hmodule, _T("GetThreadTimes") );
677 if( OurGetThreadTimes &&
678 OurGetThreadTimes( hThread,
679 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
682 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
683 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
687 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
688 kernel_ft.dwLowDateTime) / 10;
691 ((((int64_t)user_ft.dwHighDateTime)<<32)|
692 user_ft.dwLowDateTime) / 10;
694 msg_Dbg( p_this, "thread times: "
695 "real "I64Fd"m%fs, kernel "I64Fd"m%fs, user "I64Fd"m%fs",
696 real_time/60/1000000,
697 (double)((real_time%(60*1000000))/1000000.0),
698 kernel_time/60/1000000,
699 (double)((kernel_time%(60*1000000))/1000000.0),
700 user_time/60/1000000,
701 (double)((user_time%(60*1000000))/1000000.0) );
703 CloseHandle( hThread );
705 #else /* !defined(WIN32) */
709 #if defined( HAVE_KERNEL_SCHEDULER_H )
711 i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
713 #elif defined( LIBVLC_USE_PTHREAD )
714 /* Make sure we do return if we are calling vlc_thread_join()
715 * from the joined thread */
716 if (pthread_equal (pthread_self (), p_priv->thread_id))
717 i_ret = pthread_detach (p_priv->thread_id);
719 i_ret = pthread_join (p_priv->thread_id, NULL);
725 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%m)",
726 (unsigned int)p_priv->thread_id, psz_file, i_line );
730 msg_Dbg( p_this, "thread %u joined (%s:%d)",
731 (unsigned int)p_priv->thread_id, psz_file, i_line );
736 p_priv->b_thread = false;