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 *****************************************************************************/
40 #define VLC_THREADS_UNINITIALIZED 0
41 #define VLC_THREADS_PENDING 1
42 #define VLC_THREADS_ERROR 2
43 #define VLC_THREADS_READY 3
45 /*****************************************************************************
46 * Global mutex for lazy initialization of the threads system
47 *****************************************************************************/
48 static volatile unsigned i_initializations = 0;
50 #if defined( LIBVLC_USE_PTHREAD )
51 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
55 * Global process-wide VLC object.
56 * Contains inter-instance data, such as the module cache and global mutexes.
58 static libvlc_global_data_t *p_root;
60 libvlc_global_data_t *vlc_global( void )
62 assert( i_initializations > 0 );
67 * Object running the current thread
69 static vlc_threadvar_t thread_object_key;
71 vlc_object_t *vlc_threadobj (void)
73 return vlc_threadvar_get (&thread_object_key);
76 vlc_threadvar_t msg_context_global_key;
78 #if defined(LIBVLC_USE_PTHREAD)
79 static inline unsigned long vlc_threadid (void)
81 union { pthread_t th; unsigned long int i; } v = { };
82 v.th = pthread_self ();
86 /*****************************************************************************
87 * vlc_thread_fatal: Report an error from the threading layer
88 *****************************************************************************
89 * This is mostly meant for debugging.
90 *****************************************************************************/
91 void vlc_pthread_fatal (const char *action, int error,
92 const char *file, unsigned line)
94 fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
95 action, vlc_threadid (), file, line, error);
98 /* Sometimes strerror_r() crashes too, so make sure we print an error
99 * message before we invoke it */
101 /* Avoid the strerror_r() prototype brain damage in glibc */
103 fprintf (stderr, " Error message: %m\n");
108 switch (strerror_r (error, buf, sizeof (buf)))
113 case ERANGE: /* should never happen */
114 msg = "unknwon (too big to display)";
117 msg = "unknown (invalid error number)";
120 fprintf (stderr, " Error message: %s\n", msg);
127 void vlc_pthread_fatal (const char *action, int error,
128 const char *file, unsigned line)
130 (void)action; (void)error; (void)file; (void)line;
135 /*****************************************************************************
136 * vlc_threads_init: initialize threads system
137 *****************************************************************************
138 * This function requires lazy initialization of a global lock in order to
139 * keep the library really thread-safe. Some architectures don't support this
140 * and thus do not guarantee the complete reentrancy.
141 *****************************************************************************/
142 int vlc_threads_init( void )
144 int i_ret = VLC_SUCCESS;
146 /* If we have lazy mutex initialization, use it. Otherwise, we just
147 * hope nothing wrong happens. */
148 #if defined( LIBVLC_USE_PTHREAD )
149 pthread_mutex_lock( &once_mutex );
152 if( i_initializations == 0 )
154 p_root = vlc_custom_create( NULL, sizeof( *p_root ),
155 VLC_OBJECT_GENERIC, "root" );
162 /* We should be safe now. Do all the initialization stuff we want. */
163 vlc_threadvar_create( &thread_object_key, NULL );
164 vlc_threadvar_create( &msg_context_global_key, msg_StackDestroy );
169 /* If we have lazy mutex initialization support, unlock the mutex.
170 * Otherwize, we are screwed. */
171 #if defined( LIBVLC_USE_PTHREAD )
172 pthread_mutex_unlock( &once_mutex );
178 /*****************************************************************************
179 * vlc_threads_end: stop threads system
180 *****************************************************************************
181 * FIXME: This function is far from being threadsafe.
182 *****************************************************************************/
183 void vlc_threads_end( void )
185 #if defined( LIBVLC_USE_PTHREAD )
186 pthread_mutex_lock( &once_mutex );
189 assert( i_initializations > 0 );
191 if( i_initializations == 1 )
193 vlc_object_release( p_root );
194 vlc_threadvar_delete( &msg_context_global_key );
195 vlc_threadvar_delete( &thread_object_key );
199 #if defined( LIBVLC_USE_PTHREAD )
200 pthread_mutex_unlock( &once_mutex );
204 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
205 /* This is not prototyped under glibc, though it exists. */
206 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
209 /*****************************************************************************
210 * vlc_mutex_init: initialize a mutex
211 *****************************************************************************/
212 int vlc_mutex_init( vlc_mutex_t *p_mutex )
214 #if defined( LIBVLC_USE_PTHREAD )
215 pthread_mutexattr_t attr;
218 pthread_mutexattr_init( &attr );
221 /* Create error-checking mutex to detect problems more easily. */
222 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
223 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
225 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
228 i_result = pthread_mutex_init( p_mutex, &attr );
229 pthread_mutexattr_destroy( &attr );
231 #elif defined( UNDER_CE )
232 InitializeCriticalSection( &p_mutex->csection );
235 #elif defined( WIN32 )
236 *p_mutex = CreateMutex( 0, FALSE, 0 );
237 return (*p_mutex != NULL) ? 0 : ENOMEM;
239 #elif defined( HAVE_KERNEL_SCHEDULER_H )
240 /* check the arguments and whether it's already been initialized */
241 if( p_mutex == NULL )
246 if( p_mutex->init == 9999 )
251 p_mutex->lock = create_sem( 1, "BeMutex" );
252 if( p_mutex->lock < B_NO_ERROR )
257 p_mutex->init = 9999;
263 /*****************************************************************************
264 * vlc_mutex_init: initialize a recursive mutex (Do not use)
265 *****************************************************************************/
266 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
268 #if defined( LIBVLC_USE_PTHREAD )
269 pthread_mutexattr_t attr;
272 pthread_mutexattr_init( &attr );
273 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
274 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
276 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
278 i_result = pthread_mutex_init( p_mutex, &attr );
279 pthread_mutexattr_destroy( &attr );
281 #elif defined( WIN32 )
282 /* Create mutex returns a recursive mutex */
283 *p_mutex = CreateMutex( 0, FALSE, 0 );
284 return (*p_mutex != NULL) ? 0 : ENOMEM;
286 # error Unimplemented!
291 /*****************************************************************************
292 * vlc_mutex_destroy: destroy a mutex, inner version
293 *****************************************************************************/
294 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
296 #if defined( LIBVLC_USE_PTHREAD )
297 int val = pthread_mutex_destroy( p_mutex );
298 VLC_THREAD_ASSERT ("destroying mutex");
300 #elif defined( UNDER_CE )
301 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
303 DeleteCriticalSection( &p_mutex->csection );
305 #elif defined( WIN32 )
306 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
308 CloseHandle( *p_mutex );
310 #elif defined( HAVE_KERNEL_SCHEDULER_H )
311 if( p_mutex->init == 9999 )
312 delete_sem( p_mutex->lock );
319 /*****************************************************************************
320 * vlc_cond_init: initialize a condition
321 *****************************************************************************/
322 int __vlc_cond_init( vlc_cond_t *p_condvar )
324 #if defined( LIBVLC_USE_PTHREAD )
325 pthread_condattr_t attr;
328 ret = pthread_condattr_init (&attr);
332 # if !defined (_POSIX_CLOCK_SELECTION)
333 /* Fairly outdated POSIX support (that was defined in 2001) */
334 # define _POSIX_CLOCK_SELECTION (-1)
336 # if (_POSIX_CLOCK_SELECTION >= 0)
337 /* NOTE: This must be the same clock as the one in mtime.c */
338 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
341 ret = pthread_cond_init (p_condvar, &attr);
342 pthread_condattr_destroy (&attr);
345 #elif defined( UNDER_CE ) || defined( WIN32 )
346 /* Initialize counter */
347 p_condvar->i_waiting_threads = 0;
349 /* Create an auto-reset event. */
350 p_condvar->event = CreateEvent( NULL, /* no security */
351 FALSE, /* auto-reset event */
352 FALSE, /* start non-signaled */
353 NULL ); /* unnamed */
354 return !p_condvar->event;
356 #elif defined( HAVE_KERNEL_SCHEDULER_H )
362 if( p_condvar->init == 9999 )
367 p_condvar->thread = -1;
368 p_condvar->init = 9999;
374 /*****************************************************************************
375 * vlc_cond_destroy: destroy a condition, inner version
376 *****************************************************************************/
377 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
379 #if defined( LIBVLC_USE_PTHREAD )
380 int val = pthread_cond_destroy( p_condvar );
381 VLC_THREAD_ASSERT ("destroying condition");
383 #elif defined( UNDER_CE ) || defined( WIN32 )
384 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
386 CloseHandle( p_condvar->event );
388 #elif defined( HAVE_KERNEL_SCHEDULER_H )
394 /*****************************************************************************
395 * vlc_tls_create: create a thread-local variable
396 *****************************************************************************/
397 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
401 #if defined( LIBVLC_USE_PTHREAD )
402 i_ret = pthread_key_create( p_tls, destr );
403 #elif defined( UNDER_CE )
405 #elif defined( WIN32 )
407 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
409 # error Unimplemented!
414 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
416 #if defined( LIBVLC_USE_PTHREAD )
417 pthread_key_delete (*p_tls);
418 #elif defined( UNDER_CE )
419 #elif defined( WIN32 )
422 # error Unimplemented!
426 struct vlc_thread_boot
428 void * (*entry) (void *);
429 vlc_object_t *object;
432 #if defined (LIBVLC_USE_PTHREAD)
433 # define THREAD_RTYPE void *
434 # define THREAD_RVAL NULL
435 #elif defined (WIN32)
436 # define THREAD_RTYPE __stdcall unsigned
437 # define THREAD_RVAL 0
440 static THREAD_RTYPE thread_entry (void *data)
442 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
443 void *(*func) (void *) = ((struct vlc_thread_boot *)data)->entry;
446 vlc_threadvar_set (&thread_object_key, obj);
447 msg_Dbg (obj, "thread started");
449 msg_Dbg (obj, "thread ended");
453 /*****************************************************************************
454 * vlc_thread_create: create a thread, inner version
455 *****************************************************************************
456 * Note that i_priority is only taken into account on platforms supporting
457 * userland real-time priority threads.
458 *****************************************************************************/
459 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
460 const char *psz_name, void * ( *func ) ( void * ),
461 int i_priority, bool b_wait )
464 vlc_object_internals_t *p_priv = vlc_internals( p_this );
466 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
470 boot->object = p_this;
472 vlc_mutex_lock( &p_this->object_lock );
474 #if defined( LIBVLC_USE_PTHREAD )
475 sigset_t set, oldset;
477 /* We really don't want signals to (literaly) interrupt our blocking I/O
478 * system calls. SIGPIPE is especially bad, as it can be caused by remote
479 * peers through connected sockets. Generally, we cannot know which signals
480 * are handled by the main program. Also, external LibVLC bindings tend not
481 * to setup a proper signal mask before invoking LibVLC.
482 * Hence, we hereby block all signals, except those for which blocking is
483 * undefined, as listed below. Note that SIGKILL and SIGSTOP need not be
484 * listed (see the documentation for pthread_sigmask) here. */
486 sigdelset (&set, SIGFPE);
487 sigdelset (&set, SIGILL);
488 sigdelset (&set, SIGSEGV);
489 sigdelset (&set, SIGBUS);
490 pthread_sigmask (SIG_BLOCK, &set, &oldset);
492 i_ret = pthread_create( &p_priv->thread_id, NULL, thread_entry, boot );
493 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
496 if( config_GetInt( p_this, "rt-priority" ) > 0 )
499 int i_error, i_policy;
500 struct sched_param param;
502 memset( ¶m, 0, sizeof(struct sched_param) );
503 if( config_GetType( p_this, "rt-offset" ) )
504 i_priority += config_GetInt( p_this, "rt-offset" );
505 if( i_priority <= 0 )
507 param.sched_priority = (-1) * i_priority;
508 i_policy = SCHED_OTHER;
512 param.sched_priority = i_priority;
515 if( (i_error = pthread_setschedparam( p_priv->thread_id,
516 i_policy, ¶m )) )
519 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
529 #elif defined( WIN32 ) || defined( UNDER_CE )
531 /* When using the MSVCRT C library you have to use the _beginthreadex
532 * function instead of CreateThread, otherwise you'll end up with
533 * memory leaks and the signal functions not working (see Microsoft
534 * Knowledge Base, article 104641) */
535 #if defined( UNDER_CE )
536 HANDLE hThread = CreateThread( NULL, 0, thread_entry,
537 (LPVOID)boot, CREATE_SUSPENDED,
540 HANDLE hThread = (HANDLE)(uintptr_t)
541 _beginthreadex( NULL, 0, thread_entry, boot,
542 CREATE_SUSPENDED, NULL );
544 p_priv->thread_id = hThread;
545 ResumeThread(hThread);
548 i_ret = ( p_priv->thread_id ? 0 : errno );
550 if( !i_ret && i_priority )
552 if( !SetThreadPriority(p_priv->thread_id, i_priority) )
554 msg_Warn( p_this, "couldn't set a faster priority" );
559 #elif defined( HAVE_KERNEL_SCHEDULER_H )
560 p_priv->thread_id = spawn_thread( (thread_func)thread_entry, psz_name,
561 i_priority, p_data );
562 i_ret = resume_thread( p_priv->thread_id );
570 msg_Dbg( p_this, "waiting for thread completion" );
571 vlc_object_wait( p_this );
574 p_priv->b_thread = true;
575 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
576 (unsigned long)p_priv->thread_id, psz_name, i_priority,
582 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
583 psz_name, psz_file, i_line );
586 vlc_mutex_unlock( &p_this->object_lock );
590 /*****************************************************************************
591 * vlc_thread_set_priority: set the priority of the current thread when we
592 * couldn't set it in vlc_thread_create (for instance for the main thread)
593 *****************************************************************************/
594 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
595 int i_line, int i_priority )
597 vlc_object_internals_t *p_priv = vlc_internals( p_this );
599 #if defined( LIBVLC_USE_PTHREAD )
601 if( config_GetInt( p_this, "rt-priority" ) > 0 )
604 int i_error, i_policy;
605 struct sched_param param;
607 memset( ¶m, 0, sizeof(struct sched_param) );
608 if( config_GetType( p_this, "rt-offset" ) )
609 i_priority += config_GetInt( p_this, "rt-offset" );
610 if( i_priority <= 0 )
612 param.sched_priority = (-1) * i_priority;
613 i_policy = SCHED_OTHER;
617 param.sched_priority = i_priority;
620 if( !p_priv->thread_id )
621 p_priv->thread_id = pthread_self();
622 if( (i_error = pthread_setschedparam( p_priv->thread_id,
623 i_policy, ¶m )) )
626 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
632 #elif defined( WIN32 ) || defined( UNDER_CE )
633 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
635 if( !p_priv->thread_id )
636 p_priv->thread_id = GetCurrentThread();
637 if( !SetThreadPriority(p_priv->thread_id, i_priority) )
639 msg_Warn( p_this, "couldn't set a faster priority" );
648 /*****************************************************************************
649 * vlc_thread_ready: tell the parent thread we were successfully spawned
650 *****************************************************************************/
651 void __vlc_thread_ready( vlc_object_t *p_this )
653 vlc_object_signal( p_this );
656 /*****************************************************************************
657 * vlc_thread_join: wait until a thread exits, inner version
658 *****************************************************************************/
659 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
661 vlc_object_internals_t *p_priv = vlc_internals( p_this );
664 #if defined( LIBVLC_USE_PTHREAD )
665 /* Make sure we do return if we are calling vlc_thread_join()
666 * from the joined thread */
667 if (pthread_equal (pthread_self (), p_priv->thread_id))
668 i_ret = pthread_detach (p_priv->thread_id);
670 i_ret = pthread_join (p_priv->thread_id, NULL);
672 #elif defined( UNDER_CE ) || defined( WIN32 )
674 BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
675 FILETIME*, FILETIME* );
676 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
677 int64_t real_time, kernel_time, user_time;
681 ** object will close its thread handle when destroyed, duplicate it here
682 ** to be on the safe side
684 if( ! DuplicateHandle(GetCurrentProcess(),
690 DUPLICATE_SAME_ACCESS) )
692 p_priv->b_thread = false;
693 i_ret = GetLastError();
697 WaitForSingleObject( hThread, INFINITE );
699 #if defined( UNDER_CE )
700 hmodule = GetModuleHandle( _T("COREDLL") );
702 hmodule = GetModuleHandle( _T("KERNEL32") );
704 OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
705 FILETIME*, FILETIME* ))
706 GetProcAddress( hmodule, _T("GetThreadTimes") );
708 if( OurGetThreadTimes &&
709 OurGetThreadTimes( hThread,
710 &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
713 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
714 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
718 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
719 kernel_ft.dwLowDateTime) / 10;
722 ((((int64_t)user_ft.dwHighDateTime)<<32)|
723 user_ft.dwLowDateTime) / 10;
725 msg_Dbg( p_this, "thread times: "
726 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
727 real_time/60/1000000,
728 (double)((real_time%(60*1000000))/1000000.0),
729 kernel_time/60/1000000,
730 (double)((kernel_time%(60*1000000))/1000000.0),
731 user_time/60/1000000,
732 (double)((user_time%(60*1000000))/1000000.0) );
734 CloseHandle( hThread );
737 #elif defined( HAVE_KERNEL_SCHEDULER_H )
739 i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
746 msg_Err( p_this, "thread_join(%lu) failed at %s:%d (%m)",
747 (unsigned long)p_priv->thread_id, psz_file, i_line );
750 msg_Dbg( p_this, "thread %lu joined (%s:%d)",
751 (unsigned long)p_priv->thread_id, psz_file, i_line );
753 p_priv->b_thread = false;