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 vlc_object_t *p_root;
50 #if defined( UNDER_CE )
51 #elif defined( WIN32 )
52 #elif defined( HAVE_KERNEL_SCHEDULER_H )
53 #elif defined( LIBVLC_USE_PTHREAD )
54 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
57 vlc_threadvar_t msg_context_global_key;
59 #if defined(LIBVLC_USE_PTHREAD)
60 static inline unsigned long vlc_threadid (void)
62 union { pthread_t th; unsigned long int i; } v = { };
63 v.th = pthread_self ();
68 /*****************************************************************************
69 * vlc_thread_fatal: Report an error from the threading layer
70 *****************************************************************************
71 * This is mostly meant for debugging.
72 *****************************************************************************/
73 void vlc_pthread_fatal (const char *action, int error,
74 const char *file, unsigned line)
76 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
77 action, vlc_threadid (), file, line, error);
80 /* Sometimes strerror_r() crashes too, so make sure we print an error
81 * message before we invoke it */
83 /* Avoid the strerror_r() prototype brain damage in glibc */
85 fprintf (stderr, " Error message: %m\n");
90 switch (strerror_r (error, buf, sizeof (buf)))
95 case ERANGE: /* should never happen */
96 msg = "unknwon (too big to display)";
99 msg = "unknown (invalid error number)";
102 fprintf (stderr, " Error message: %s\n", msg);
111 /*****************************************************************************
112 * vlc_threads_init: initialize threads system
113 *****************************************************************************
114 * This function requires lazy initialization of a global lock in order to
115 * keep the library really thread-safe. Some architectures don't support this
116 * and thus do not guarantee the complete reentrancy.
117 *****************************************************************************/
118 int __vlc_threads_init( vlc_object_t *p_this )
120 libvlc_global_data_t *p_libvlc_global = (libvlc_global_data_t *)p_this;
121 int i_ret = VLC_SUCCESS;
123 /* If we have lazy mutex initialization, use it. Otherwise, we just
124 * hope nothing wrong happens. */
125 #if defined( UNDER_CE )
126 #elif defined( WIN32 )
127 #elif defined( HAVE_KERNEL_SCHEDULER_H )
128 #elif defined( LIBVLC_USE_PTHREAD )
129 pthread_mutex_lock( &once_mutex );
132 if( i_initializations == 0 )
134 /* We should be safe now. Do all the initialization stuff we want. */
135 p_libvlc_global->b_ready = false;
137 p_root = vlc_custom_create( VLC_OBJECT(p_libvlc_global), 0,
138 VLC_OBJECT_GLOBAL, "global" );
144 vlc_threadvar_create( p_root, &msg_context_global_key );
149 /* If we have lazy mutex initialization support, unlock the mutex.
150 * Otherwize, we are screwed. */
151 #if defined( UNDER_CE )
152 #elif defined( WIN32 )
153 #elif defined( HAVE_KERNEL_SCHEDULER_H )
154 #elif defined( LIBVLC_USE_PTHREAD )
155 pthread_mutex_unlock( &once_mutex );
161 /*****************************************************************************
162 * vlc_threads_end: stop threads system
163 *****************************************************************************
164 * FIXME: This function is far from being threadsafe.
165 *****************************************************************************/
166 int __vlc_threads_end( vlc_object_t *p_this )
169 #if defined( UNDER_CE )
170 #elif defined( WIN32 )
171 #elif defined( HAVE_KERNEL_SCHEDULER_H )
172 #elif defined( LIBVLC_USE_PTHREAD )
173 pthread_mutex_lock( &once_mutex );
176 assert( i_initializations > 0 );
177 if( --i_initializations == 0 )
178 vlc_object_release( p_root );
180 #if defined( UNDER_CE )
181 #elif defined( WIN32 )
182 #elif defined( HAVE_KERNEL_SCHEDULER_H )
183 #elif defined( LIBVLC_USE_PTHREAD )
184 pthread_mutex_unlock( &once_mutex );
190 /* This is not prototyped under Linux, though it exists. */
191 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
194 /*****************************************************************************
195 * vlc_mutex_init: initialize a mutex
196 *****************************************************************************/
197 int __vlc_mutex_init( vlc_mutex_t *p_mutex )
199 #if defined( UNDER_CE )
200 InitializeCriticalSection( &p_mutex->csection );
203 #elif defined( WIN32 )
204 *p_mutex = CreateMutex( 0, FALSE, 0 );
205 return (*p_mutex != NULL) ? 0 : ENOMEM;
207 #elif defined( HAVE_KERNEL_SCHEDULER_H )
208 /* check the arguments and whether it's already been initialized */
209 if( p_mutex == NULL )
214 if( p_mutex->init == 9999 )
219 p_mutex->lock = create_sem( 1, "BeMutex" );
220 if( p_mutex->lock < B_NO_ERROR )
225 p_mutex->init = 9999;
228 #elif defined( LIBVLC_USE_PTHREAD )
229 pthread_mutexattr_t attr;
232 pthread_mutexattr_init( &attr );
235 /* Create error-checking mutex to detect problems more easily. */
236 # if defined(SYS_LINUX)
237 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
239 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
242 i_result = pthread_mutex_init( p_mutex, &attr );
243 pthread_mutexattr_destroy( &attr );
248 /*****************************************************************************
249 * vlc_mutex_init: initialize a recursive mutex (Do not use)
250 *****************************************************************************/
251 int __vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
254 /* Create mutex returns a recursive mutex */
255 *p_mutex = CreateMutex( 0, FALSE, 0 );
256 return (*p_mutex != NULL) ? 0 : ENOMEM;
257 #elif defined( LIBVLC_USE_PTHREAD )
258 pthread_mutexattr_t attr;
261 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 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
271 i_result = pthread_mutex_init( p_mutex, &attr );
272 pthread_mutexattr_destroy( &attr );
275 # error Unimplemented!
280 /*****************************************************************************
281 * vlc_mutex_destroy: destroy a mutex, inner version
282 *****************************************************************************/
283 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
285 #if defined( UNDER_CE )
286 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
288 DeleteCriticalSection( &p_mutex->csection );
290 #elif defined( WIN32 )
291 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
293 CloseHandle( *p_mutex );
295 #elif defined( HAVE_KERNEL_SCHEDULER_H )
296 if( p_mutex->init == 9999 )
297 delete_sem( p_mutex->lock );
301 #elif defined( LIBVLC_USE_PTHREAD )
302 int val = pthread_mutex_destroy( p_mutex );
303 VLC_THREAD_ASSERT ("destroying mutex");
308 /*****************************************************************************
309 * vlc_cond_init: initialize a condition
310 *****************************************************************************/
311 int __vlc_cond_init( vlc_cond_t *p_condvar )
313 #if defined( UNDER_CE ) || defined( WIN32 )
314 /* Initialize counter */
315 p_condvar->i_waiting_threads = 0;
317 /* Create an auto-reset event. */
318 p_condvar->event = CreateEvent( NULL, /* no security */
319 FALSE, /* auto-reset event */
320 FALSE, /* start non-signaled */
321 NULL ); /* unnamed */
322 return !p_condvar->event;
324 #elif defined( HAVE_KERNEL_SCHEDULER_H )
330 if( p_condvar->init == 9999 )
335 p_condvar->thread = -1;
336 p_condvar->init = 9999;
339 #elif defined( LIBVLC_USE_PTHREAD )
340 pthread_condattr_t attr;
343 ret = pthread_condattr_init (&attr);
347 # if !defined (_POSIX_CLOCK_SELECTION)
348 /* Fairly outdated POSIX support (that was defined in 2001) */
349 # define _POSIX_CLOCK_SELECTION (-1)
351 # if (_POSIX_CLOCK_SELECTION >= 0)
352 /* NOTE: This must be the same clock as the one in mtime.c */
353 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
356 ret = pthread_cond_init (p_condvar, &attr);
357 pthread_condattr_destroy (&attr);
363 /*****************************************************************************
364 * vlc_cond_destroy: destroy a condition, inner version
365 *****************************************************************************/
366 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
368 #if defined( UNDER_CE ) || defined( WIN32 )
369 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
371 CloseHandle( p_condvar->event );
373 #elif defined( HAVE_KERNEL_SCHEDULER_H )
376 #elif defined( LIBVLC_USE_PTHREAD )
377 int val = pthread_cond_destroy( p_condvar );
378 VLC_THREAD_ASSERT ("destroying condition");
383 /*****************************************************************************
384 * vlc_tls_create: create a thread-local variable
385 *****************************************************************************/
386 int __vlc_threadvar_create( vlc_threadvar_t *p_tls )
390 #if defined( HAVE_KERNEL_SCHEDULER_H )
391 # error Unimplemented!
392 #elif defined( UNDER_CE )
393 #elif defined( WIN32 )
395 i_ret = (*p_tls == INVALID_HANDLE_VALUE) ? EAGAIN : 0;
397 #elif defined( LIBVLC_USE_PTHREAD )
398 i_ret = pthread_key_create( p_tls, NULL );
403 /*****************************************************************************
404 * vlc_thread_create: create a thread, inner version
405 *****************************************************************************
406 * Note that i_priority is only taken into account on platforms supporting
407 * userland real-time priority threads.
408 *****************************************************************************/
409 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
410 const char *psz_name, void * ( *func ) ( void * ),
411 int i_priority, bool b_wait )
414 void *p_data = (void *)p_this;
415 vlc_object_internals_t *p_priv = vlc_internals( p_this );
417 vlc_mutex_lock( &p_this->object_lock );
419 #if defined( WIN32 ) || defined( UNDER_CE )
421 /* When using the MSVCRT C library you have to use the _beginthreadex
422 * function instead of CreateThread, otherwise you'll end up with
423 * memory leaks and the signal functions not working (see Microsoft
424 * Knowledge Base, article 104641) */
425 #if defined( UNDER_CE )
427 HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
428 (LPVOID)p_data, CREATE_SUSPENDED,
432 uintptr_t hThread = _beginthreadex( NULL, 0,
433 (LPTHREAD_START_ROUTINE)func,
434 (void*)p_data, CREATE_SUSPENDED,
437 p_priv->thread_id.id = (DWORD)threadId;
438 p_priv->thread_id.hThread = (HANDLE)hThread;
439 ResumeThread((HANDLE)hThread);
442 i_ret = ( p_priv->thread_id.hThread ? 0 : 1 );
444 if( !i_ret && i_priority )
446 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
448 msg_Warn( p_this, "couldn't set a faster priority" );
453 #elif defined( HAVE_KERNEL_SCHEDULER_H )
454 p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
455 i_priority, p_data );
456 i_ret = resume_thread( p_priv->thread_id );
458 #elif defined( LIBVLC_USE_PTHREAD )
459 i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
462 if( config_GetInt( p_this, "rt-priority" ) )
465 int i_error, i_policy;
466 struct sched_param param;
468 memset( ¶m, 0, sizeof(struct sched_param) );
469 if( config_GetType( p_this, "rt-offset" ) )
471 i_priority += config_GetInt( p_this, "rt-offset" );
473 if( i_priority <= 0 )
475 param.sched_priority = (-1) * i_priority;
476 i_policy = SCHED_OTHER;
480 param.sched_priority = i_priority;
483 if( (i_error = pthread_setschedparam( p_priv->thread_id,
484 i_policy, ¶m )) )
487 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
505 msg_Dbg( p_this, "waiting for thread completion" );
506 vlc_object_wait( p_this );
509 p_priv->b_thread = true;
511 #if defined( WIN32 ) || defined( UNDER_CE )
512 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
513 (unsigned int)p_priv->thread_id.id, psz_name,
514 i_priority, psz_file, i_line );
516 msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
517 (unsigned int)p_priv->thread_id, psz_name, i_priority,
522 vlc_mutex_unlock( &p_this->object_lock );
527 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
528 psz_name, psz_file, i_line );
529 vlc_mutex_unlock( &p_this->object_lock );
535 /*****************************************************************************
536 * vlc_thread_set_priority: set the priority of the current thread when we
537 * couldn't set it in vlc_thread_create (for instance for the main thread)
538 *****************************************************************************/
539 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
540 int i_line, int i_priority )
542 vlc_object_internals_t *p_priv = vlc_internals( p_this );
543 #if defined( WIN32 ) || defined( UNDER_CE )
544 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
546 if( !p_priv->thread_id.hThread )
547 p_priv->thread_id.hThread = GetCurrentThread();
548 if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
550 msg_Warn( p_this, "couldn't set a faster priority" );
554 #elif defined( LIBVLC_USE_PTHREAD )
556 if( config_GetInt( p_this, "rt-priority" ) > 0 )
559 int i_error, i_policy;
560 struct sched_param param;
562 memset( ¶m, 0, sizeof(struct sched_param) );
563 if( config_GetType( p_this, "rt-offset" ) )
565 i_priority += config_GetInt( p_this, "rt-offset" );
567 if( i_priority <= 0 )
569 param.sched_priority = (-1) * i_priority;
570 i_policy = SCHED_OTHER;
574 param.sched_priority = i_priority;
577 if( !p_priv->thread_id )
578 p_priv->thread_id = pthread_self();
579 if( (i_error = pthread_setschedparam( p_priv->thread_id,
580 i_policy, ¶m )) )
583 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
593 /*****************************************************************************
594 * vlc_thread_ready: tell the parent thread we were successfully spawned
595 *****************************************************************************/
596 void __vlc_thread_ready( vlc_object_t *p_this )
598 vlc_object_signal( p_this );
601 /*****************************************************************************
602 * vlc_thread_join: wait until a thread exits, inner version
603 *****************************************************************************/
604 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
606 vlc_object_internals_t *p_priv = vlc_internals( p_this );
608 #if defined( UNDER_CE ) || defined( WIN32 )
610 BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
611 FILETIME*, FILETIME* );
612 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
613 int64_t real_time, kernel_time, user_time;
617 ** object will close its thread handle when destroyed, duplicate it here
618 ** to be on the safe side
620 if( ! DuplicateHandle(GetCurrentProcess(),
621 p_priv->thread_id.hThread,
626 DUPLICATE_SAME_ACCESS) )
628 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%u)",
629 (unsigned int)p_priv->thread_id.id,
630 psz_file, i_line, (unsigned int)GetLastError() );
631 p_priv->b_thread = false;
635 WaitForSingleObject( hThread, INFINITE );
637 msg_Dbg( p_this, "thread %u joined (%s:%d)",
638 (unsigned int)p_priv->thread_id.id,
640 #if defined( UNDER_CE )
641 hmodule = GetModuleHandle( _T("COREDLL") );
643 hmodule = GetModuleHandle( _T("KERNEL32") );
645 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
646 FILETIME*, FILETIME* ))
647 GetProcAddress( hmodule, _T("GetThreadTimes") );
649 if( OurGetThreadTimes &&
650 OurGetThreadTimes( hThread,
651 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
654 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
655 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
659 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
660 kernel_ft.dwLowDateTime) / 10;
663 ((((int64_t)user_ft.dwHighDateTime)<<32)|
664 user_ft.dwLowDateTime) / 10;
666 msg_Dbg( p_this, "thread times: "
667 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
668 real_time/60/1000000,
669 (double)((real_time%(60*1000000))/1000000.0),
670 kernel_time/60/1000000,
671 (double)((kernel_time%(60*1000000))/1000000.0),
672 user_time/60/1000000,
673 (double)((user_time%(60*1000000))/1000000.0) );
675 CloseHandle( hThread );
677 #else /* !defined(WIN32) */
681 #if defined( HAVE_KERNEL_SCHEDULER_H )
683 i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
685 #elif defined( LIBVLC_USE_PTHREAD )
686 /* Make sure we do return if we are calling vlc_thread_join()
687 * from the joined thread */
688 if (pthread_equal (pthread_self (), p_priv->thread_id))
689 i_ret = pthread_detach (p_priv->thread_id);
691 i_ret = pthread_join (p_priv->thread_id, NULL);
697 msg_Err( p_this, "thread_join(%u) failed at %s:%d (%m)",
698 (unsigned int)p_priv->thread_id, psz_file, i_line );
702 msg_Dbg( p_this, "thread %u joined (%s:%d)",
703 (unsigned int)p_priv->thread_id, psz_file, i_line );
708 p_priv->b_thread = false;