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>
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26 *****************************************************************************/
32 #include <vlc_common.h>
42 /*****************************************************************************
43 * Global mutex for lazy initialization of the threads system
44 *****************************************************************************/
45 static volatile unsigned i_initializations = 0;
47 #if defined( LIBVLC_USE_PTHREAD )
50 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
52 static vlc_threadvar_t cancel_key;
56 * Global process-wide VLC object.
57 * Contains the global named mutexes.
60 static vlc_object_t *p_root;
62 #ifdef HAVE_EXECINFO_H
63 # include <execinfo.h>
67 * Print a backtrace to the standard error for debugging purpose.
69 void vlc_trace (const char *fn, const char *file, unsigned line)
71 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
72 fflush (stderr); /* needed before switch to low-level I/O */
75 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
76 backtrace_symbols_fd (stack, len, 2);
83 static inline unsigned long vlc_threadid (void)
85 #if defined(LIBVLC_USE_PTHREAD)
86 union { pthread_t th; unsigned long int i; } v = { };
87 v.th = pthread_self ();
91 return GetCurrentThreadId ();
99 /*****************************************************************************
100 * vlc_thread_fatal: Report an error from the threading layer
101 *****************************************************************************
102 * This is mostly meant for debugging.
103 *****************************************************************************/
105 vlc_thread_fatal (const char *action, int error,
106 const char *function, const char *file, unsigned line)
108 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
109 action, error, vlc_threadid ());
110 vlc_trace (function, file, line);
112 /* Sometimes strerror_r() crashes too, so make sure we print an error
113 * message before we invoke it */
115 /* Avoid the strerror_r() prototype brain damage in glibc */
117 fprintf (stderr, " Error message: %m\n");
118 #elif !defined (WIN32)
122 switch (strerror_r (error, buf, sizeof (buf)))
127 case ERANGE: /* should never happen */
128 msg = "unknwon (too big to display)";
131 msg = "unknown (invalid error number)";
134 fprintf (stderr, " Error message: %s\n", msg);
142 # define VLC_THREAD_ASSERT( action ) \
143 if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
145 # define VLC_THREAD_ASSERT( action ) ((void)val)
149 * Per-thread cancellation data
151 #ifndef LIBVLC_USE_PTHREAD_CANCEL
152 typedef struct vlc_cancel_t
154 vlc_cleanup_t *cleaners;
159 # define VLC_CANCEL_INIT { NULL, true, false }
162 /*****************************************************************************
163 * vlc_threads_init: initialize threads system
164 *****************************************************************************
165 * This function requires lazy initialization of a global lock in order to
166 * keep the library really thread-safe. Some architectures don't support this
167 * and thus do not guarantee the complete reentrancy.
168 *****************************************************************************/
169 int vlc_threads_init( void )
171 int i_ret = VLC_SUCCESS;
173 /* If we have lazy mutex initialization, use it. Otherwise, we just
174 * hope nothing wrong happens. */
175 #if defined( LIBVLC_USE_PTHREAD )
176 pthread_mutex_lock( &once_mutex );
179 if( i_initializations == 0 )
181 p_root = vlc_custom_create( (vlc_object_t *)NULL, sizeof( *p_root ),
182 VLC_OBJECT_GENERIC, "root" );
189 /* We should be safe now. Do all the initialization stuff we want. */
190 #ifndef LIBVLC_USE_PTHREAD_CANCEL
191 vlc_threadvar_create( &cancel_key, free );
197 /* If we have lazy mutex initialization support, unlock the mutex.
198 * Otherwize, we are screwed. */
199 #if defined( LIBVLC_USE_PTHREAD )
200 pthread_mutex_unlock( &once_mutex );
206 /*****************************************************************************
207 * vlc_threads_end: stop threads system
208 *****************************************************************************
209 * FIXME: This function is far from being threadsafe.
210 *****************************************************************************/
211 void vlc_threads_end( void )
213 #if defined( LIBVLC_USE_PTHREAD )
214 pthread_mutex_lock( &once_mutex );
217 assert( i_initializations > 0 );
219 if( i_initializations == 1 )
221 vlc_object_release( p_root );
222 #ifndef LIBVLC_USE_PTHREAD
223 vlc_threadvar_delete( &cancel_key );
228 #if defined( LIBVLC_USE_PTHREAD )
229 pthread_mutex_unlock( &once_mutex );
233 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
234 /* This is not prototyped under glibc, though it exists. */
235 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
238 /*****************************************************************************
239 * vlc_mutex_init: initialize a mutex
240 *****************************************************************************/
241 int vlc_mutex_init( vlc_mutex_t *p_mutex )
243 #if defined( LIBVLC_USE_PTHREAD )
244 pthread_mutexattr_t attr;
247 pthread_mutexattr_init( &attr );
250 /* Create error-checking mutex to detect problems more easily. */
251 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
252 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
254 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
257 i_result = pthread_mutex_init( p_mutex, &attr );
258 pthread_mutexattr_destroy( &attr );
261 #elif defined( WIN32 )
262 InitializeCriticalSection (&p_mutex->mutex);
263 p_mutex->recursive = false;
269 /*****************************************************************************
270 * vlc_mutex_init: initialize a recursive mutex (Do not use)
271 *****************************************************************************/
272 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
274 #if defined( LIBVLC_USE_PTHREAD )
275 pthread_mutexattr_t attr;
278 pthread_mutexattr_init( &attr );
279 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
280 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
282 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
284 i_result = pthread_mutex_init( p_mutex, &attr );
285 pthread_mutexattr_destroy( &attr );
288 #elif defined( WIN32 )
289 InitializeCriticalSection( &p_mutex->mutex );
290 p_mutex->owner = 0; /* the error value for GetThreadId()! */
291 p_mutex->recursion = 0;
292 p_mutex->recursive = true;
300 * Destroys a mutex. The mutex must not be locked.
302 * @param p_mutex mutex to destroy
303 * @return always succeeds
305 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
307 #if defined( LIBVLC_USE_PTHREAD )
308 int val = pthread_mutex_destroy( p_mutex );
309 VLC_THREAD_ASSERT ("destroying mutex");
311 #elif defined( WIN32 )
312 DeleteCriticalSection (&p_mutex->mutex);
318 * Acquires a mutex. If needed, waits for any other thread to release it.
319 * Beware of deadlocks when locking multiple mutexes at the same time,
320 * or when using mutexes from callbacks.
322 * @param p_mutex mutex initialized with vlc_mutex_init() or
323 * vlc_mutex_init_recursive()
325 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
327 #if defined(LIBVLC_USE_PTHREAD)
328 int val = pthread_mutex_lock( p_mutex );
329 VLC_THREAD_ASSERT ("locking mutex");
331 #elif defined( WIN32 )
332 if (p_mutex->recursive)
334 DWORD self = GetCurrentThreadId ();
336 if ((DWORD)InterlockedCompareExchange (&p_mutex->owner, self,
338 { /* We already locked this recursive mutex */
339 p_mutex->recursion++;
343 /* We need to lock this recursive mutex */
344 EnterCriticalSection (&p_mutex->mutex);
345 self = InterlockedExchange (&p_mutex->owner, self);
346 assert (self == 0); /* no previous owner */
349 /* Non-recursive mutex */
350 EnterCriticalSection (&p_mutex->mutex);
357 * Releases a mutex (or crashes if the mutex is not locked by the caller).
358 * @param p_mutex mutex locked with vlc_mutex_lock().
360 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
362 #if defined(LIBVLC_USE_PTHREAD)
363 int val = pthread_mutex_unlock( p_mutex );
364 VLC_THREAD_ASSERT ("unlocking mutex");
366 #elif defined( WIN32 )
367 if (p_mutex->recursive)
369 if (p_mutex->recursion != 0)
371 p_mutex->recursion--;
372 return; /* We still own this mutex */
375 /* We release the mutex */
376 InterlockedExchange (&p_mutex->owner, 0);
379 LeaveCriticalSection (&p_mutex->mutex);
384 /*****************************************************************************
385 * vlc_cond_init: initialize a condition variable
386 *****************************************************************************/
387 int vlc_cond_init( vlc_cond_t *p_condvar )
389 #if defined( LIBVLC_USE_PTHREAD )
390 pthread_condattr_t attr;
393 ret = pthread_condattr_init (&attr);
397 # if !defined (_POSIX_CLOCK_SELECTION)
398 /* Fairly outdated POSIX support (that was defined in 2001) */
399 # define _POSIX_CLOCK_SELECTION (-1)
401 # if (_POSIX_CLOCK_SELECTION >= 0)
402 /* NOTE: This must be the same clock as the one in mtime.c */
403 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
406 ret = pthread_cond_init (p_condvar, &attr);
407 pthread_condattr_destroy (&attr);
410 #elif defined( WIN32 )
411 /* Create a manual-reset event (manual reset is needed for broadcast). */
412 *p_condvar = CreateEvent( NULL, TRUE, FALSE, NULL );
413 return *p_condvar ? 0 : ENOMEM;
419 * Destroys a condition variable. No threads shall be waiting or signaling the
421 * @param p_condvar condition variable to destroy
423 void vlc_cond_destroy (vlc_cond_t *p_condvar)
425 #if defined( LIBVLC_USE_PTHREAD )
426 int val = pthread_cond_destroy( p_condvar );
427 VLC_THREAD_ASSERT ("destroying condition");
429 #elif defined( WIN32 )
430 CloseHandle( *p_condvar );
436 * Wakes up one thread waiting on a condition variable, if any.
437 * @param p_condvar condition variable
439 void vlc_cond_signal (vlc_cond_t *p_condvar)
441 #if defined(LIBVLC_USE_PTHREAD)
442 int val = pthread_cond_signal( p_condvar );
443 VLC_THREAD_ASSERT ("signaling condition variable");
445 #elif defined( WIN32 )
446 /* NOTE: This will cause a broadcast, that is wrong.
447 * This will also wake up the next waiting thread if no thread are yet
448 * waiting, which is also wrong. However both of these issues are allowed
449 * by the provision for spurious wakeups. Better have too many wakeups
450 * than too few (= deadlocks). */
451 SetEvent (*p_condvar);
457 * Wakes up all threads (if any) waiting on a condition variable.
458 * @param p_cond condition variable
460 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
462 #if defined (LIBVLC_USE_PTHREAD)
463 pthread_cond_broadcast (p_condvar);
465 #elif defined (WIN32)
466 SetEvent (*p_condvar);
473 # define WaitForMultipleObjectsEx(a,b,c) WaitForMultipleObjects(a,b)
477 * Waits for a condition variable. The calling thread will be suspended until
478 * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
479 * condition variable, the thread is cancelled with vlc_cancel(), or the
480 * system causes a "spurious" unsolicited wake-up.
482 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
483 * a recursive mutex. Although it is possible to use the same mutex for
484 * multiple condition, it is not valid to use different mutexes for the same
485 * condition variable at the same time from different threads.
487 * In case of thread cancellation, the mutex is always locked before
488 * cancellation proceeds.
490 * The canonical way to use a condition variable to wait for event foobar is:
492 vlc_mutex_lock (&lock);
493 mutex_cleanup_push (&lock); // release the mutex in case of cancellation
496 vlc_cond_wait (&wait, &lock);
498 --- foobar is now true, do something about it here --
500 vlc_cleanup_run (); // release the mutex
503 * @param p_condvar condition variable to wait on
504 * @param p_mutex mutex which is unlocked while waiting,
505 * then locked again when waking up.
506 * @param deadline <b>absolute</b> timeout
508 * @return 0 if the condition was signaled, an error code in case of timeout.
510 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
512 #if defined(LIBVLC_USE_PTHREAD)
513 int val = pthread_cond_wait( p_condvar, p_mutex );
514 VLC_THREAD_ASSERT ("waiting on condition");
516 #elif defined( WIN32 )
519 assert (!p_mutex->recursive);
523 LeaveCriticalSection (&p_mutex->mutex);
524 result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
525 EnterCriticalSection (&p_mutex->mutex);
527 while (result == WAIT_IO_COMPLETION);
529 ResetEvent (*p_condvar);
535 * Waits for a condition variable up to a certain date.
536 * This works like vlc_cond_wait(), except for the additional timeout.
538 * @param p_condvar condition variable to wait on
539 * @param p_mutex mutex which is unlocked while waiting,
540 * then locked again when waking up.
541 * @param deadline <b>absolute</b> timeout
543 * @return 0 if the condition was signaled, an error code in case of timeout.
545 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
548 #if defined(LIBVLC_USE_PTHREAD)
549 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
550 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
552 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
553 if (val != ETIMEDOUT)
554 VLC_THREAD_ASSERT ("timed-waiting on condition");
557 #elif defined( WIN32 )
560 assert (!p_mutex->recursive);
565 mtime_t total = (deadline - mdate ())/1000;
569 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
570 LeaveCriticalSection (&p_mutex->mutex);
571 result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
572 EnterCriticalSection (&p_mutex->mutex);
574 while (result == WAIT_IO_COMPLETION);
576 ResetEvent (*p_condvar);
578 return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
583 /*****************************************************************************
584 * vlc_tls_create: create a thread-local variable
585 *****************************************************************************/
586 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
590 #if defined( LIBVLC_USE_PTHREAD )
591 i_ret = pthread_key_create( p_tls, destr );
592 #elif defined( UNDER_CE )
594 #elif defined( WIN32 )
595 /* FIXME: remember/use the destr() callback and stop leaking whatever */
597 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
599 # error Unimplemented!
604 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
606 #if defined( LIBVLC_USE_PTHREAD )
607 pthread_key_delete (*p_tls);
608 #elif defined( UNDER_CE )
609 #elif defined( WIN32 )
612 # error Unimplemented!
616 #if defined (LIBVLC_USE_PTHREAD)
617 #elif defined (WIN32)
618 static unsigned __stdcall vlc_entry (void *data)
620 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
621 vlc_thread_t self = data;
623 vlc_threadvar_set (&cancel_key, &cancel_data);
624 self->data = self->entry (self->data);
630 * Creates and starts new thread.
632 * @param p_handle [OUT] pointer to write the handle of the created thread to
633 * @param entry entry point for the thread
634 * @param data data parameter given to the entry point
635 * @param priority thread priority value
636 * @return 0 on success, a standard error code on error.
638 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
643 #if defined( LIBVLC_USE_PTHREAD )
645 pthread_attr_init (&attr);
647 /* Block the signals that signals interface plugin handles.
648 * If the LibVLC caller wants to handle some signals by itself, it should
649 * block these before whenever invoking LibVLC. And it must obviously not
650 * start the VLC signals interface plugin.
652 * LibVLC will normally ignore any interruption caused by an asynchronous
653 * signal during a system call. But there may well be some buggy cases
654 * where it fails to handle EINTR (bug reports welcome). Some underlying
655 * libraries might also not handle EINTR properly.
661 sigdelset (&set, SIGHUP);
662 sigaddset (&set, SIGINT);
663 sigaddset (&set, SIGQUIT);
664 sigaddset (&set, SIGTERM);
666 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
667 pthread_sigmask (SIG_BLOCK, &set, &oldset);
670 struct sched_param sp = { .sched_priority = priority, };
673 if (sp.sched_priority <= 0)
674 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
676 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
678 pthread_attr_setschedpolicy (&attr, policy);
679 pthread_attr_setschedparam (&attr, &sp);
682 /* The thread stack size.
683 * The lower the value, the less address space per thread, the highest
684 * maximum simultaneous threads per process. Too low values will cause
685 * stack overflows and weird crashes. Set with caution. Also keep in mind
686 * that 64-bits platforms consume more stack than 32-bits one.
688 * Thanks to on-demand paging, thread stack size only affects address space
689 * consumption. In terms of memory, threads only use what they need
690 * (rounded up to the page boundary).
692 * For example, on Linux i386, the default is 2 mega-bytes, which supports
693 * about 320 threads per processes. */
694 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
697 ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
698 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
701 ret = pthread_create (p_handle, &attr, entry, data);
702 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
703 pthread_attr_destroy (&attr);
705 #elif defined( WIN32 ) || defined( UNDER_CE )
706 /* When using the MSVCRT C library you have to use the _beginthreadex
707 * function instead of CreateThread, otherwise you'll end up with
708 * memory leaks and the signal functions not working (see Microsoft
709 * Knowledge Base, article 104641) */
711 vlc_thread_t th = malloc (sizeof (*th));
718 #if defined( UNDER_CE )
719 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
721 hThread = (HANDLE)(uintptr_t)
722 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
727 /* Thread closes the handle when exiting, duplicate it here
728 * to be on the safe side when joining. */
729 if (!DuplicateHandle (GetCurrentProcess (), hThread,
730 GetCurrentProcess (), &th->handle, 0, FALSE,
731 DUPLICATE_SAME_ACCESS))
733 CloseHandle (hThread);
738 ResumeThread (hThread);
740 SetThreadPriority (hThread, priority);
756 /* APC procedure for thread cancellation */
757 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
760 vlc_control_cancel (VLC_DO_CANCEL);
765 * Marks a thread as cancelled. Next time the target thread reaches a
766 * cancellation point (while not having disabled cancellation), it will
767 * run its cancellation cleanup handler, the thread variable destructors, and
768 * terminate. vlc_join() must be used afterward regardless of a thread being
771 void vlc_cancel (vlc_thread_t thread_id)
773 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
774 pthread_cancel (thread_id);
775 #elif defined (WIN32)
776 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
778 # warning vlc_cancel is not implemented!
783 * Waits for a thread to complete (if needed), and destroys it.
784 * This is a cancellation point; in case of cancellation, the join does _not_
787 * @param handle thread handle
788 * @param p_result [OUT] pointer to write the thread return value or NULL
789 * @return 0 on success, a standard error code otherwise.
791 void vlc_join (vlc_thread_t handle, void **result)
793 #if defined( LIBVLC_USE_PTHREAD )
794 int val = pthread_join (handle, result);
796 vlc_thread_fatal ("joining thread", val, __func__, __FILE__, __LINE__);
798 #elif defined( UNDER_CE ) || defined( WIN32 )
801 while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
802 == WAIT_IO_COMPLETION);
804 CloseHandle (handle->handle);
806 *result = handle->data;
813 struct vlc_thread_boot
815 void * (*entry) (vlc_object_t *);
816 vlc_object_t *object;
819 static void *thread_entry (void *data)
821 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
822 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
825 msg_Dbg (obj, "thread started");
827 msg_Dbg (obj, "thread ended");
832 /*****************************************************************************
833 * vlc_thread_create: create a thread, inner version
834 *****************************************************************************
835 * Note that i_priority is only taken into account on platforms supporting
836 * userland real-time priority threads.
837 *****************************************************************************/
838 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
839 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
840 int i_priority, bool b_wait )
843 vlc_object_internals_t *p_priv = vlc_internals( p_this );
845 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
849 boot->object = p_this;
851 vlc_object_lock( p_this );
853 /* Make sure we don't re-create a thread if the object has already one */
854 assert( !p_priv->b_thread );
856 #if defined( LIBVLC_USE_PTHREAD )
858 if( config_GetInt( p_this, "rt-priority" ) > 0 )
861 /* Hack to avoid error msg */
862 if( config_GetType( p_this, "rt-offset" ) )
863 i_priority += config_GetInt( p_this, "rt-offset" );
867 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
872 msg_Dbg( p_this, "waiting for thread initialization" );
873 vlc_object_wait( p_this );
876 p_priv->b_thread = true;
877 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
878 (unsigned long)p_priv->thread_id, psz_name, i_priority,
884 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
885 psz_name, psz_file, i_line );
888 vlc_object_unlock( p_this );
892 /*****************************************************************************
893 * vlc_thread_set_priority: set the priority of the current thread when we
894 * couldn't set it in vlc_thread_create (for instance for the main thread)
895 *****************************************************************************/
896 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
897 int i_line, int i_priority )
899 vlc_object_internals_t *p_priv = vlc_internals( p_this );
901 if( !p_priv->b_thread )
903 msg_Err( p_this, "couldn't set priority of non-existent thread" );
907 #if defined( LIBVLC_USE_PTHREAD )
909 if( config_GetInt( p_this, "rt-priority" ) > 0 )
912 int i_error, i_policy;
913 struct sched_param param;
915 memset( ¶m, 0, sizeof(struct sched_param) );
916 if( config_GetType( p_this, "rt-offset" ) )
917 i_priority += config_GetInt( p_this, "rt-offset" );
918 if( i_priority <= 0 )
920 param.sched_priority = (-1) * i_priority;
921 i_policy = SCHED_OTHER;
925 param.sched_priority = i_priority;
928 if( (i_error = pthread_setschedparam( p_priv->thread_id,
929 i_policy, ¶m )) )
932 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
938 #elif defined( WIN32 ) || defined( UNDER_CE )
939 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
941 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
943 msg_Warn( p_this, "couldn't set a faster priority" );
952 /*****************************************************************************
953 * vlc_thread_join: wait until a thread exits, inner version
954 *****************************************************************************/
955 void __vlc_thread_join( vlc_object_t *p_this )
957 vlc_object_internals_t *p_priv = vlc_internals( p_this );
959 #if defined( LIBVLC_USE_PTHREAD )
960 vlc_join (p_priv->thread_id, NULL);
962 #elif defined( UNDER_CE ) || defined( WIN32 )
964 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
965 int64_t real_time, kernel_time, user_time;
967 if( ! DuplicateHandle(GetCurrentProcess(),
968 p_priv->thread_id->handle,
973 DUPLICATE_SAME_ACCESS) )
975 p_priv->b_thread = false;
976 return; /* We have a problem! */
979 vlc_join( p_priv->thread_id, NULL );
981 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
984 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
985 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
989 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
990 kernel_ft.dwLowDateTime) / 10;
993 ((((int64_t)user_ft.dwHighDateTime)<<32)|
994 user_ft.dwLowDateTime) / 10;
996 msg_Dbg( p_this, "thread times: "
997 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
998 real_time/60/1000000,
999 (double)((real_time%(60*1000000))/1000000.0),
1000 kernel_time/60/1000000,
1001 (double)((kernel_time%(60*1000000))/1000000.0),
1002 user_time/60/1000000,
1003 (double)((user_time%(60*1000000))/1000000.0) );
1005 CloseHandle( hThread );
1008 vlc_join( p_priv->thread_id, NULL );
1012 p_priv->b_thread = false;
1015 void vlc_thread_cancel (vlc_object_t *obj)
1017 vlc_object_internals_t *priv = vlc_internals (obj);
1020 vlc_cancel (priv->thread_id);
1023 void vlc_control_cancel (int cmd, ...)
1025 /* NOTE: This function only modifies thread-specific data, so there is no
1026 * need to lock anything. */
1027 #ifdef LIBVLC_USE_PTHREAD_CANCEL
1033 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
1037 /* Main thread - cannot be cancelled anyway */
1040 nfo = malloc (sizeof (*nfo));
1042 return; /* Uho! Expect problems! */
1043 *nfo = VLC_CANCEL_INIT;
1044 vlc_threadvar_set (&cancel_key, nfo);
1051 case VLC_SAVE_CANCEL:
1053 int *p_state = va_arg (ap, int *);
1054 *p_state = nfo->killable;
1055 nfo->killable = false;
1059 case VLC_RESTORE_CANCEL:
1061 int state = va_arg (ap, int);
1062 nfo->killable = state != 0;
1066 case VLC_TEST_CANCEL:
1067 if (nfo->killable && nfo->killed)
1069 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
1074 #if defined (LIBVLC_USE_PTHREAD)
1075 pthread_exit (PTHREAD_CANCELLED);
1076 #elif defined (WIN32)
1079 # error Not implemented!
1088 case VLC_CLEANUP_PUSH:
1090 /* cleaner is a pointer to the caller stack, no need to allocate
1091 * and copy anything. As a nice side effect, this cannot fail. */
1092 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
1093 cleaner->next = nfo->cleaners;
1094 nfo->cleaners = cleaner;
1098 case VLC_CLEANUP_POP:
1100 nfo->cleaners = nfo->cleaners->next;
1109 #undef var_AcquireMutex
1111 * Finds a process-wide mutex, creates it if needed, and locks it.
1112 * Unlock with vlc_mutex_unlock().
1114 vlc_mutex_t *var_AcquireMutex( const char *name )
1118 if( var_Create( p_root, name, VLC_VAR_MUTEX ) )
1121 var_Get( p_root, name, &val );
1122 vlc_mutex_lock( val.p_address );
1123 return val.p_address;