1 /*****************************************************************************
2 * threads.c : threads implementation for the VideoLAN client
3 *****************************************************************************
4 * Copyright (C) 1999-2008 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 *****************************************************************************/
31 #include <vlc_common.h>
41 #define VLC_THREADS_UNINITIALIZED 0
42 #define VLC_THREADS_PENDING 1
43 #define VLC_THREADS_ERROR 2
44 #define VLC_THREADS_READY 3
46 /*****************************************************************************
47 * Global mutex for lazy initialization of the threads system
48 *****************************************************************************/
49 static volatile unsigned i_initializations = 0;
51 #if defined( LIBVLC_USE_PTHREAD )
54 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
56 static vlc_threadvar_t cancel_key;
60 * Global process-wide VLC object.
61 * Contains inter-instance data, such as the module cache and global mutexes.
63 static libvlc_global_data_t *p_root;
65 libvlc_global_data_t *vlc_global( void )
67 assert( i_initializations > 0 );
71 #ifdef HAVE_EXECINFO_H
72 # include <execinfo.h>
76 * Print a backtrace to the standard error for debugging purpose.
78 void vlc_trace (const char *fn, const char *file, unsigned line)
80 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
81 fflush (stderr); /* needed before switch to low-level I/O */
84 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
85 backtrace_symbols_fd (stack, len, 2);
92 static inline unsigned long vlc_threadid (void)
94 #if defined(LIBVLC_USE_PTHREAD)
95 union { pthread_t th; unsigned long int i; } v = { };
96 v.th = pthread_self ();
100 return GetCurrentThreadId ();
108 /*****************************************************************************
109 * vlc_thread_fatal: Report an error from the threading layer
110 *****************************************************************************
111 * This is mostly meant for debugging.
112 *****************************************************************************/
113 void vlc_thread_fatal (const char *action, int error, const char *function,
114 const char *file, unsigned line)
116 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
117 action, error, vlc_threadid ());
118 vlc_trace (function, file, line);
120 /* Sometimes strerror_r() crashes too, so make sure we print an error
121 * message before we invoke it */
123 /* Avoid the strerror_r() prototype brain damage in glibc */
125 fprintf (stderr, " Error message: %m at:\n");
126 #elif !defined (WIN32)
130 switch (strerror_r (error, buf, sizeof (buf)))
135 case ERANGE: /* should never happen */
136 msg = "unknwon (too big to display)";
139 msg = "unknown (invalid error number)";
142 fprintf (stderr, " Error message: %s\n", msg);
150 * Per-thread cancellation data
152 #ifndef LIBVLC_USE_PTHREAD_CANCEL
153 typedef struct vlc_cancel_t
155 vlc_cleanup_t *cleaners;
160 # define VLC_CANCEL_INIT { NULL, false, true }
163 /*****************************************************************************
164 * vlc_threads_init: initialize threads system
165 *****************************************************************************
166 * This function requires lazy initialization of a global lock in order to
167 * keep the library really thread-safe. Some architectures don't support this
168 * and thus do not guarantee the complete reentrancy.
169 *****************************************************************************/
170 int vlc_threads_init( void )
172 int i_ret = VLC_SUCCESS;
174 /* If we have lazy mutex initialization, use it. Otherwise, we just
175 * hope nothing wrong happens. */
176 #if defined( LIBVLC_USE_PTHREAD )
177 pthread_mutex_lock( &once_mutex );
180 if( i_initializations == 0 )
182 p_root = vlc_custom_create( (vlc_object_t *)NULL, sizeof( *p_root ),
183 VLC_OBJECT_GENERIC, "root" );
190 /* We should be safe now. Do all the initialization stuff we want. */
191 #ifndef LIBVLC_USE_PTHREAD_CANCEL
192 vlc_threadvar_create( &cancel_key, free );
198 /* If we have lazy mutex initialization support, unlock the mutex.
199 * Otherwize, we are screwed. */
200 #if defined( LIBVLC_USE_PTHREAD )
201 pthread_mutex_unlock( &once_mutex );
207 /*****************************************************************************
208 * vlc_threads_end: stop threads system
209 *****************************************************************************
210 * FIXME: This function is far from being threadsafe.
211 *****************************************************************************/
212 void vlc_threads_end( void )
214 #if defined( LIBVLC_USE_PTHREAD )
215 pthread_mutex_lock( &once_mutex );
218 assert( i_initializations > 0 );
220 if( i_initializations == 1 )
222 vlc_object_release( p_root );
223 #ifndef LIBVLC_USE_PTHREAD
224 vlc_threadvar_delete( &cancel_key );
229 #if defined( LIBVLC_USE_PTHREAD )
230 pthread_mutex_unlock( &once_mutex );
234 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
235 /* This is not prototyped under glibc, though it exists. */
236 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
239 /*****************************************************************************
240 * vlc_mutex_init: initialize a mutex
241 *****************************************************************************/
242 int vlc_mutex_init( vlc_mutex_t *p_mutex )
244 #if defined( LIBVLC_USE_PTHREAD )
245 pthread_mutexattr_t attr;
248 pthread_mutexattr_init( &attr );
251 /* Create error-checking mutex to detect problems more easily. */
252 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
253 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
255 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
258 i_result = pthread_mutex_init( p_mutex, &attr );
259 pthread_mutexattr_destroy( &attr );
261 #elif defined( UNDER_CE )
262 InitializeCriticalSection( &p_mutex->csection );
265 #elif defined( WIN32 )
266 *p_mutex = CreateMutex( 0, FALSE, 0 );
267 return (*p_mutex != NULL) ? 0 : ENOMEM;
272 /*****************************************************************************
273 * vlc_mutex_init: initialize a recursive mutex (Do not use)
274 *****************************************************************************/
275 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
277 #if defined( LIBVLC_USE_PTHREAD )
278 pthread_mutexattr_t attr;
281 pthread_mutexattr_init( &attr );
282 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
283 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
285 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
287 i_result = pthread_mutex_init( p_mutex, &attr );
288 pthread_mutexattr_destroy( &attr );
290 #elif defined( WIN32 )
291 /* Create mutex returns a recursive mutex */
292 *p_mutex = CreateMutex( 0, FALSE, 0 );
293 return (*p_mutex != NULL) ? 0 : ENOMEM;
295 # error Unimplemented!
300 /*****************************************************************************
301 * vlc_mutex_destroy: destroy a mutex, inner version
302 *****************************************************************************/
303 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
305 #if defined( LIBVLC_USE_PTHREAD )
306 int val = pthread_mutex_destroy( p_mutex );
307 VLC_THREAD_ASSERT ("destroying mutex");
309 #elif defined( UNDER_CE )
310 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
312 DeleteCriticalSection( &p_mutex->csection );
314 #elif defined( WIN32 )
315 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
317 CloseHandle( *p_mutex );
322 /*****************************************************************************
323 * vlc_cond_init: initialize a condition variable
324 *****************************************************************************/
325 int vlc_cond_init( vlc_cond_t *p_condvar )
327 #if defined( LIBVLC_USE_PTHREAD )
328 pthread_condattr_t attr;
331 ret = pthread_condattr_init (&attr);
335 # if !defined (_POSIX_CLOCK_SELECTION)
336 /* Fairly outdated POSIX support (that was defined in 2001) */
337 # define _POSIX_CLOCK_SELECTION (-1)
339 # if (_POSIX_CLOCK_SELECTION >= 0)
340 /* NOTE: This must be the same clock as the one in mtime.c */
341 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
344 ret = pthread_cond_init (p_condvar, &attr);
345 pthread_condattr_destroy (&attr);
348 #elif defined( UNDER_CE ) || defined( WIN32 )
349 /* Create an auto-reset event. */
350 *p_condvar = CreateEvent( NULL, /* no security */
351 FALSE, /* auto-reset event */
352 FALSE, /* start non-signaled */
353 NULL ); /* unnamed */
354 return *p_condvar ? 0 : ENOMEM;
359 /*****************************************************************************
360 * vlc_cond_destroy: destroy a condition, inner version
361 *****************************************************************************/
362 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
364 #if defined( LIBVLC_USE_PTHREAD )
365 int val = pthread_cond_destroy( p_condvar );
366 VLC_THREAD_ASSERT ("destroying condition");
368 #elif defined( UNDER_CE ) || defined( WIN32 )
369 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
371 CloseHandle( *p_condvar );
376 /*****************************************************************************
377 * vlc_tls_create: create a thread-local variable
378 *****************************************************************************/
379 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
383 #if defined( LIBVLC_USE_PTHREAD )
384 i_ret = pthread_key_create( p_tls, destr );
385 #elif defined( UNDER_CE )
387 #elif defined( WIN32 )
388 /* FIXME: remember/use the destr() callback and stop leaking whatever */
390 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
392 # error Unimplemented!
397 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
399 #if defined( LIBVLC_USE_PTHREAD )
400 pthread_key_delete (*p_tls);
401 #elif defined( UNDER_CE )
402 #elif defined( WIN32 )
405 # error Unimplemented!
409 #if defined (LIBVLC_USE_PTHREAD)
410 #elif defined (WIN32)
411 static unsigned __stdcall vlc_entry (void *data)
413 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
414 vlc_thread_t self = data;
416 vlc_threadvar_set (&cancel_key, &cancel_data);
417 self->data = self->entry (self->data);
423 * Creates and starts new thread.
425 * @param p_handle [OUT] pointer to write the handle of the created thread to
426 * @param entry entry point for the thread
427 * @param data data parameter given to the entry point
428 * @param priority thread priority value
429 * @return 0 on success, a standard error code on error.
431 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
436 #if defined( LIBVLC_USE_PTHREAD )
438 pthread_attr_init (&attr);
440 /* Block the signals that signals interface plugin handles.
441 * If the LibVLC caller wants to handle some signals by itself, it should
442 * block these before whenever invoking LibVLC. And it must obviously not
443 * start the VLC signals interface plugin.
445 * LibVLC will normally ignore any interruption caused by an asynchronous
446 * signal during a system call. But there may well be some buggy cases
447 * where it fails to handle EINTR (bug reports welcome). Some underlying
448 * libraries might also not handle EINTR properly.
454 sigdelset (&set, SIGHUP);
455 sigaddset (&set, SIGINT);
456 sigaddset (&set, SIGQUIT);
457 sigaddset (&set, SIGTERM);
459 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
460 pthread_sigmask (SIG_BLOCK, &set, &oldset);
463 struct sched_param sp = { .sched_priority = priority, };
466 if (sp.sched_priority <= 0)
467 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
469 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
471 pthread_attr_setschedpolicy (&attr, policy);
472 pthread_attr_setschedparam (&attr, &sp);
475 ret = pthread_create (p_handle, &attr, entry, data);
476 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
477 pthread_attr_destroy (&attr);
479 #elif defined( WIN32 ) || defined( UNDER_CE )
480 /* When using the MSVCRT C library you have to use the _beginthreadex
481 * function instead of CreateThread, otherwise you'll end up with
482 * memory leaks and the signal functions not working (see Microsoft
483 * Knowledge Base, article 104641) */
485 vlc_thread_t th = malloc (sizeof (*th));
492 #if defined( UNDER_CE )
493 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
495 hThread = (HANDLE)(uintptr_t)
496 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
501 /* Thread closes the handle when exiting, duplicate it here
502 * to be on the safe side when joining. */
503 if (!DuplicateHandle (GetCurrentProcess (), hThread,
504 GetCurrentProcess (), &th->handle, 0, FALSE,
505 DUPLICATE_SAME_ACCESS))
507 CloseHandle (hThread);
512 ResumeThread (hThread);
514 SetThreadPriority (hThread, priority);
530 /* APC procedure for thread cancellation */
531 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
534 vlc_control_cancel (VLC_DO_CANCEL);
539 * Marks a thread as cancelled. Next time the target thread reaches a
540 * cancellation point (while not having disabled cancellation), it will
541 * run its cancellation cleanup handler, the thread variable destructors, and
542 * terminate. vlc_join() must be used afterward regardless of a thread being
545 void vlc_cancel (vlc_thread_t thread_id)
547 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
548 pthread_cancel (thread_id);
549 #elif defined (WIN32)
550 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
552 # warning vlc_cancel is not implemented!
557 * Waits for a thread to complete (if needed), and destroys it.
558 * This is a cancellation point; in case of cancellation, the join does _not_
561 * @param handle thread handle
562 * @param p_result [OUT] pointer to write the thread return value or NULL
563 * @return 0 on success, a standard error code otherwise.
565 void vlc_join (vlc_thread_t handle, void **result)
567 #if defined( LIBVLC_USE_PTHREAD )
568 int val = pthread_join (handle, result);
570 vlc_thread_fatal ("joining thread", val, __func__, __FILE__, __LINE__);
572 #elif defined( UNDER_CE ) || defined( WIN32 )
575 while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
576 == WAIT_IO_COMPLETION);
578 CloseHandle (handle->handle);
580 *result = handle->data;
587 struct vlc_thread_boot
589 void * (*entry) (vlc_object_t *);
590 vlc_object_t *object;
593 static void *thread_entry (void *data)
595 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
596 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
599 msg_Dbg (obj, "thread started");
601 msg_Dbg (obj, "thread ended");
606 /*****************************************************************************
607 * vlc_thread_create: create a thread, inner version
608 *****************************************************************************
609 * Note that i_priority is only taken into account on platforms supporting
610 * userland real-time priority threads.
611 *****************************************************************************/
612 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
613 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
614 int i_priority, bool b_wait )
617 vlc_object_internals_t *p_priv = vlc_internals( p_this );
619 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
623 boot->object = p_this;
625 vlc_object_lock( p_this );
627 /* Make sure we don't re-create a thread if the object has already one */
628 assert( !p_priv->b_thread );
630 #if defined( LIBVLC_USE_PTHREAD )
632 if( config_GetInt( p_this, "rt-priority" ) > 0 )
635 /* Hack to avoid error msg */
636 if( config_GetType( p_this, "rt-offset" ) )
637 i_priority += config_GetInt( p_this, "rt-offset" );
641 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
646 msg_Dbg( p_this, "waiting for thread initialization" );
647 vlc_object_wait( p_this );
650 p_priv->b_thread = true;
651 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
652 (unsigned long)p_priv->thread_id, psz_name, i_priority,
658 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
659 psz_name, psz_file, i_line );
662 vlc_object_unlock( p_this );
666 /*****************************************************************************
667 * vlc_thread_set_priority: set the priority of the current thread when we
668 * couldn't set it in vlc_thread_create (for instance for the main thread)
669 *****************************************************************************/
670 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
671 int i_line, int i_priority )
673 vlc_object_internals_t *p_priv = vlc_internals( p_this );
675 if( !p_priv->b_thread )
677 msg_Err( p_this, "couldn't set priority of non-existent thread" );
681 #if defined( LIBVLC_USE_PTHREAD )
683 if( config_GetInt( p_this, "rt-priority" ) > 0 )
686 int i_error, i_policy;
687 struct sched_param param;
689 memset( ¶m, 0, sizeof(struct sched_param) );
690 if( config_GetType( p_this, "rt-offset" ) )
691 i_priority += config_GetInt( p_this, "rt-offset" );
692 if( i_priority <= 0 )
694 param.sched_priority = (-1) * i_priority;
695 i_policy = SCHED_OTHER;
699 param.sched_priority = i_priority;
702 if( (i_error = pthread_setschedparam( p_priv->thread_id,
703 i_policy, ¶m )) )
706 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
712 #elif defined( WIN32 ) || defined( UNDER_CE )
713 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
715 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
717 msg_Warn( p_this, "couldn't set a faster priority" );
726 /*****************************************************************************
727 * vlc_thread_join: wait until a thread exits, inner version
728 *****************************************************************************/
729 void __vlc_thread_join( vlc_object_t *p_this )
731 vlc_object_internals_t *p_priv = vlc_internals( p_this );
733 #if defined( LIBVLC_USE_PTHREAD )
734 vlc_join (p_priv->thread_id, NULL);
736 #elif defined( UNDER_CE ) || defined( WIN32 )
738 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
739 int64_t real_time, kernel_time, user_time;
741 if( ! DuplicateHandle(GetCurrentProcess(),
742 p_priv->thread_id->handle,
747 DUPLICATE_SAME_ACCESS) )
749 p_priv->b_thread = false;
750 return; /* We have a problem! */
753 vlc_join( p_priv->thread_id, NULL );
755 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
758 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
759 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
763 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
764 kernel_ft.dwLowDateTime) / 10;
767 ((((int64_t)user_ft.dwHighDateTime)<<32)|
768 user_ft.dwLowDateTime) / 10;
770 msg_Dbg( p_this, "thread times: "
771 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
772 real_time/60/1000000,
773 (double)((real_time%(60*1000000))/1000000.0),
774 kernel_time/60/1000000,
775 (double)((kernel_time%(60*1000000))/1000000.0),
776 user_time/60/1000000,
777 (double)((user_time%(60*1000000))/1000000.0) );
779 CloseHandle( hThread );
782 vlc_join( p_priv->thread_id, NULL );
786 p_priv->b_thread = false;
789 void vlc_thread_cancel (vlc_object_t *obj)
791 vlc_object_internals_t *priv = vlc_internals (obj);
794 vlc_cancel (priv->thread_id);
797 void vlc_control_cancel (int cmd, ...)
799 /* NOTE: This function only modifies thread-specific data, so there is no
800 * need to lock anything. */
801 #ifdef LIBVLC_USE_PTHREAD_CANCEL
807 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
811 /* Main thread - cannot be cancelled anyway */
814 nfo = malloc (sizeof (*nfo));
816 return; /* Uho! Expect problems! */
817 *nfo = VLC_CANCEL_INIT;
818 vlc_threadvar_set (&cancel_key, nfo);
825 case VLC_SAVE_CANCEL:
827 int *p_state = va_arg (ap, int *);
828 *p_state = nfo->killable;
829 nfo->killable = false;
833 case VLC_RESTORE_CANCEL:
835 int state = va_arg (ap, int);
836 nfo->killable = state != 0;
840 case VLC_TEST_CANCEL:
841 if (nfo->killable && nfo->killed)
843 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
846 #if defined (LIBVLC_USE_PTHREAD)
847 pthread_exit (PTHREAD_CANCELLED);
848 #elif defined (WIN32)
851 # error Not implemented!
860 case VLC_CLEANUP_PUSH:
862 /* cleaner is a pointer to the caller stack, no need to allocate
863 * and copy anything. As a nice side effect, this cannot fail. */
864 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
865 cleaner->next = nfo->cleaners;
866 nfo->cleaners = cleaner;
870 case VLC_CLEANUP_POP:
872 nfo->cleaners = nfo->cleaners->next;