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 * Object running the current thread
68 static vlc_threadvar_t thread_object_key;
70 vlc_object_t *vlc_threadobj (void)
72 return vlc_threadvar_get (&thread_object_key);
75 vlc_threadvar_t msg_context_global_key;
77 #if defined(LIBVLC_USE_PTHREAD)
78 static inline unsigned long vlc_threadid (void)
80 union { pthread_t th; unsigned long int i; } v = { };
81 v.th = pthread_self ();
85 /*****************************************************************************
86 * vlc_thread_fatal: Report an error from the threading layer
87 *****************************************************************************
88 * This is mostly meant for debugging.
89 *****************************************************************************/
90 void vlc_pthread_fatal (const char *action, int error,
91 const char *file, unsigned line)
93 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
94 action, vlc_threadid (), file, line, error);
97 /* Sometimes strerror_r() crashes too, so make sure we print an error
98 * message before we invoke it */
100 /* Avoid the strerror_r() prototype brain damage in glibc */
102 fprintf (stderr, " Error message: %m\n");
107 switch (strerror_r (error, buf, sizeof (buf)))
112 case ERANGE: /* should never happen */
113 msg = "unknwon (too big to display)";
116 msg = "unknown (invalid error number)";
119 fprintf (stderr, " Error message: %s\n", msg);
126 void vlc_pthread_fatal (const char *action, int error,
127 const char *file, unsigned line)
129 (void)action; (void)error; (void)file; (void)line;
134 /*****************************************************************************
135 * vlc_threads_init: initialize threads system
136 *****************************************************************************
137 * This function requires lazy initialization of a global lock in order to
138 * keep the library really thread-safe. Some architectures don't support this
139 * and thus do not guarantee the complete reentrancy.
140 *****************************************************************************/
141 int vlc_threads_init( void )
143 int i_ret = VLC_SUCCESS;
145 /* If we have lazy mutex initialization, use it. Otherwise, we just
146 * hope nothing wrong happens. */
147 #if defined( LIBVLC_USE_PTHREAD )
148 pthread_mutex_lock( &once_mutex );
151 if( i_initializations == 0 )
153 p_root = vlc_custom_create( NULL, sizeof( *p_root ),
154 VLC_OBJECT_GENERIC, "root" );
161 /* We should be safe now. Do all the initialization stuff we want. */
162 vlc_threadvar_create( &thread_object_key, NULL );
163 vlc_threadvar_create( &msg_context_global_key, msg_StackDestroy );
168 /* If we have lazy mutex initialization support, unlock the mutex.
169 * Otherwize, we are screwed. */
170 #if defined( LIBVLC_USE_PTHREAD )
171 pthread_mutex_unlock( &once_mutex );
177 /*****************************************************************************
178 * vlc_threads_end: stop threads system
179 *****************************************************************************
180 * FIXME: This function is far from being threadsafe.
181 *****************************************************************************/
182 void vlc_threads_end( void )
184 #if defined( LIBVLC_USE_PTHREAD )
185 pthread_mutex_lock( &once_mutex );
188 assert( i_initializations > 0 );
190 if( i_initializations == 1 )
192 vlc_object_release( p_root );
193 vlc_threadvar_delete( &msg_context_global_key );
194 vlc_threadvar_delete( &thread_object_key );
198 #if defined( LIBVLC_USE_PTHREAD )
199 pthread_mutex_unlock( &once_mutex );
203 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
204 /* This is not prototyped under glibc, though it exists. */
205 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
208 /*****************************************************************************
209 * vlc_mutex_init: initialize a mutex
210 *****************************************************************************/
211 int vlc_mutex_init( vlc_mutex_t *p_mutex )
213 #if defined( LIBVLC_USE_PTHREAD )
214 pthread_mutexattr_t attr;
217 pthread_mutexattr_init( &attr );
220 /* Create error-checking mutex to detect problems more easily. */
221 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
222 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
224 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
227 i_result = pthread_mutex_init( p_mutex, &attr );
228 pthread_mutexattr_destroy( &attr );
230 #elif defined( UNDER_CE )
231 InitializeCriticalSection( &p_mutex->csection );
234 #elif defined( WIN32 )
235 *p_mutex = CreateMutex( 0, FALSE, 0 );
236 return (*p_mutex != NULL) ? 0 : ENOMEM;
238 #elif defined( HAVE_KERNEL_SCHEDULER_H )
239 /* check the arguments and whether it's already been initialized */
240 if( p_mutex == NULL )
245 if( p_mutex->init == 9999 )
250 p_mutex->lock = create_sem( 1, "BeMutex" );
251 if( p_mutex->lock < B_NO_ERROR )
256 p_mutex->init = 9999;
262 /*****************************************************************************
263 * vlc_mutex_init: initialize a recursive mutex (Do not use)
264 *****************************************************************************/
265 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
267 #if defined( LIBVLC_USE_PTHREAD )
268 pthread_mutexattr_t attr;
271 pthread_mutexattr_init( &attr );
272 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
273 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
275 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
277 i_result = pthread_mutex_init( p_mutex, &attr );
278 pthread_mutexattr_destroy( &attr );
280 #elif defined( WIN32 )
281 /* Create mutex returns a recursive mutex */
282 *p_mutex = CreateMutex( 0, FALSE, 0 );
283 return (*p_mutex != NULL) ? 0 : ENOMEM;
285 # error Unimplemented!
290 /*****************************************************************************
291 * vlc_mutex_destroy: destroy a mutex, inner version
292 *****************************************************************************/
293 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
295 #if defined( LIBVLC_USE_PTHREAD )
296 int val = pthread_mutex_destroy( p_mutex );
297 VLC_THREAD_ASSERT ("destroying mutex");
299 #elif defined( UNDER_CE )
300 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
302 DeleteCriticalSection( &p_mutex->csection );
304 #elif defined( WIN32 )
305 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
307 CloseHandle( *p_mutex );
309 #elif defined( HAVE_KERNEL_SCHEDULER_H )
310 if( p_mutex->init == 9999 )
311 delete_sem( p_mutex->lock );
318 /*****************************************************************************
319 * vlc_cond_init: initialize a condition
320 *****************************************************************************/
321 int __vlc_cond_init( vlc_cond_t *p_condvar )
323 #if defined( LIBVLC_USE_PTHREAD )
324 pthread_condattr_t attr;
327 ret = pthread_condattr_init (&attr);
331 # if !defined (_POSIX_CLOCK_SELECTION)
332 /* Fairly outdated POSIX support (that was defined in 2001) */
333 # define _POSIX_CLOCK_SELECTION (-1)
335 # if (_POSIX_CLOCK_SELECTION >= 0)
336 /* NOTE: This must be the same clock as the one in mtime.c */
337 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
340 ret = pthread_cond_init (p_condvar, &attr);
341 pthread_condattr_destroy (&attr);
344 #elif defined( UNDER_CE ) || defined( WIN32 )
345 /* Initialize counter */
346 p_condvar->i_waiting_threads = 0;
348 /* Create an auto-reset event. */
349 p_condvar->event = CreateEvent( NULL, /* no security */
350 FALSE, /* auto-reset event */
351 FALSE, /* start non-signaled */
352 NULL ); /* unnamed */
353 return !p_condvar->event;
355 #elif defined( HAVE_KERNEL_SCHEDULER_H )
361 if( p_condvar->init == 9999 )
366 p_condvar->thread = -1;
367 p_condvar->init = 9999;
373 /*****************************************************************************
374 * vlc_cond_destroy: destroy a condition, inner version
375 *****************************************************************************/
376 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
378 #if defined( LIBVLC_USE_PTHREAD )
379 int val = pthread_cond_destroy( p_condvar );
380 VLC_THREAD_ASSERT ("destroying condition");
382 #elif defined( UNDER_CE ) || defined( WIN32 )
383 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
385 CloseHandle( p_condvar->event );
387 #elif defined( HAVE_KERNEL_SCHEDULER_H )
393 /*****************************************************************************
394 * vlc_tls_create: create a thread-local variable
395 *****************************************************************************/
396 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
400 #if defined( LIBVLC_USE_PTHREAD )
401 i_ret = pthread_key_create( p_tls, destr );
402 #elif defined( UNDER_CE )
404 #elif defined( WIN32 )
406 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
408 # error Unimplemented!
413 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
415 #if defined( LIBVLC_USE_PTHREAD )
416 pthread_key_delete (*p_tls);
417 #elif defined( UNDER_CE )
418 #elif defined( WIN32 )
421 # error Unimplemented!
425 struct vlc_thread_boot
427 void * (*entry) (void *);
428 vlc_object_t *object;
431 #if defined (LIBVLC_USE_PTHREAD)
432 # define THREAD_RTYPE void *
433 # define THREAD_RVAL NULL
434 #elif defined (WIN32)
435 # define THREAD_RTYPE __stdcall unsigned
436 # define THREAD_RVAL 0
439 static THREAD_RTYPE thread_entry (void *data)
441 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
442 void *(*func) (void *) = ((struct vlc_thread_boot *)data)->entry;
445 vlc_threadvar_set (&thread_object_key, obj);
446 msg_Dbg (obj, "thread started");
448 msg_Dbg (obj, "thread ended");
452 /*****************************************************************************
453 * vlc_thread_create: create a thread, inner version
454 *****************************************************************************
455 * Note that i_priority is only taken into account on platforms supporting
456 * userland real-time priority threads.
457 *****************************************************************************/
458 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
459 const char *psz_name, void * ( *func ) ( void * ),
460 int i_priority, bool b_wait )
463 vlc_object_internals_t *p_priv = vlc_internals( p_this );
465 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
469 boot->object = p_this;
471 vlc_mutex_lock( &p_this->object_lock );
473 #if defined( LIBVLC_USE_PTHREAD )
474 i_ret = pthread_create( &p_priv->thread_id, NULL, thread_entry, boot );
477 if( config_GetInt( p_this, "rt-priority" ) > 0 )
480 int i_error, i_policy;
481 struct sched_param param;
483 memset( ¶m, 0, sizeof(struct sched_param) );
484 if( config_GetType( p_this, "rt-offset" ) )
485 i_priority += config_GetInt( p_this, "rt-offset" );
486 if( i_priority <= 0 )
488 param.sched_priority = (-1) * i_priority;
489 i_policy = SCHED_OTHER;
493 param.sched_priority = i_priority;
496 if( (i_error = pthread_setschedparam( p_priv->thread_id,
497 i_policy, ¶m )) )
500 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
510 #elif defined( WIN32 ) || defined( UNDER_CE )
512 /* When using the MSVCRT C library you have to use the _beginthreadex
513 * function instead of CreateThread, otherwise you'll end up with
514 * memory leaks and the signal functions not working (see Microsoft
515 * Knowledge Base, article 104641) */
516 #if defined( UNDER_CE )
517 HANDLE hThread = CreateThread( NULL, 0, thread_entry,
518 (LPVOID)boot, CREATE_SUSPENDED,
521 HANDLE hThread = (HANDLE)(uintptr_t)
522 _beginthreadex( NULL, 0, thread_entry, boot,
523 CREATE_SUSPENDED, NULL );
525 p_priv->thread_id = hThread;
526 ResumeThread(hThread);
529 i_ret = ( p_priv->thread_id ? 0 : errno );
531 if( !i_ret && i_priority )
533 if( !SetThreadPriority(p_priv->thread_id, i_priority) )
535 msg_Warn( p_this, "couldn't set a faster priority" );
540 #elif defined( HAVE_KERNEL_SCHEDULER_H )
541 p_priv->thread_id = spawn_thread( (thread_func)thread_entry, psz_name,
542 i_priority, p_data );
543 i_ret = resume_thread( p_priv->thread_id );
551 msg_Dbg( p_this, "waiting for thread completion" );
552 vlc_object_wait( p_this );
555 p_priv->b_thread = true;
556 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
557 (unsigned long)p_priv->thread_id, psz_name, i_priority,
563 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
564 psz_name, psz_file, i_line );
567 vlc_mutex_unlock( &p_this->object_lock );
571 /*****************************************************************************
572 * vlc_thread_set_priority: set the priority of the current thread when we
573 * couldn't set it in vlc_thread_create (for instance for the main thread)
574 *****************************************************************************/
575 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
576 int i_line, int i_priority )
578 vlc_object_internals_t *p_priv = vlc_internals( p_this );
580 #if defined( LIBVLC_USE_PTHREAD )
582 if( config_GetInt( p_this, "rt-priority" ) > 0 )
585 int i_error, i_policy;
586 struct sched_param param;
588 memset( ¶m, 0, sizeof(struct sched_param) );
589 if( config_GetType( p_this, "rt-offset" ) )
590 i_priority += config_GetInt( p_this, "rt-offset" );
591 if( i_priority <= 0 )
593 param.sched_priority = (-1) * i_priority;
594 i_policy = SCHED_OTHER;
598 param.sched_priority = i_priority;
601 if( !p_priv->thread_id )
602 p_priv->thread_id = pthread_self();
603 if( (i_error = pthread_setschedparam( p_priv->thread_id,
604 i_policy, ¶m )) )
607 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
613 #elif defined( WIN32 ) || defined( UNDER_CE )
614 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
616 if( !p_priv->thread_id )
617 p_priv->thread_id = GetCurrentThread();
618 if( !SetThreadPriority(p_priv->thread_id, i_priority) )
620 msg_Warn( p_this, "couldn't set a faster priority" );
629 /*****************************************************************************
630 * vlc_thread_ready: tell the parent thread we were successfully spawned
631 *****************************************************************************/
632 void __vlc_thread_ready( vlc_object_t *p_this )
634 vlc_object_signal( p_this );
637 /*****************************************************************************
638 * vlc_thread_join: wait until a thread exits, inner version
639 *****************************************************************************/
640 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
642 vlc_object_internals_t *p_priv = vlc_internals( p_this );
645 #if defined( LIBVLC_USE_PTHREAD )
646 /* Make sure we do return if we are calling vlc_thread_join()
647 * from the joined thread */
648 if (pthread_equal (pthread_self (), p_priv->thread_id))
649 i_ret = pthread_detach (p_priv->thread_id);
651 i_ret = pthread_join (p_priv->thread_id, NULL);
653 #elif defined( UNDER_CE ) || defined( WIN32 )
655 BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
656 FILETIME*, FILETIME* );
657 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
658 int64_t real_time, kernel_time, user_time;
662 ** object will close its thread handle when destroyed, duplicate it here
663 ** to be on the safe side
665 if( ! DuplicateHandle(GetCurrentProcess(),
671 DUPLICATE_SAME_ACCESS) )
673 p_priv->b_thread = false;
674 i_ret = GetLastError();
678 WaitForSingleObject( hThread, INFINITE );
680 #if defined( UNDER_CE )
681 hmodule = GetModuleHandle( _T("COREDLL") );
683 hmodule = GetModuleHandle( _T("KERNEL32") );
685 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
686 FILETIME*, FILETIME* ))
687 GetProcAddress( hmodule, _T("GetThreadTimes") );
689 if( OurGetThreadTimes &&
690 OurGetThreadTimes( hThread,
691 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
694 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
695 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
699 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
700 kernel_ft.dwLowDateTime) / 10;
703 ((((int64_t)user_ft.dwHighDateTime)<<32)|
704 user_ft.dwLowDateTime) / 10;
706 msg_Dbg( p_this, "thread times: "
707 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
708 real_time/60/1000000,
709 (double)((real_time%(60*1000000))/1000000.0),
710 kernel_time/60/1000000,
711 (double)((kernel_time%(60*1000000))/1000000.0),
712 user_time/60/1000000,
713 (double)((user_time%(60*1000000))/1000000.0) );
715 CloseHandle( hThread );
718 #elif defined( HAVE_KERNEL_SCHEDULER_H )
720 i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
727 msg_Err( p_this, "thread_join(%lu) failed at %s:%d (%m)",
728 (unsigned long)p_priv->thread_id, psz_file, i_line );
731 msg_Dbg( p_this, "thread %lu joined (%s:%d)",
732 (unsigned long)p_priv->thread_id, psz_file, i_line );
734 p_priv->b_thread = false;