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 #define VLC_THREADS_UNINITIALIZED 0
43 #define VLC_THREADS_PENDING 1
44 #define VLC_THREADS_ERROR 2
45 #define VLC_THREADS_READY 3
47 /*****************************************************************************
48 * Global mutex for lazy initialization of the threads system
49 *****************************************************************************/
50 static volatile unsigned i_initializations = 0;
52 #if defined( LIBVLC_USE_PTHREAD )
55 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
57 static vlc_threadvar_t cancel_key;
61 * Global process-wide VLC object.
62 * Contains inter-instance data, such as the module cache and global mutexes.
64 static libvlc_global_data_t *p_root;
66 libvlc_global_data_t *vlc_global( void )
68 assert( i_initializations > 0 );
72 #ifdef HAVE_EXECINFO_H
73 # include <execinfo.h>
77 * Print a backtrace to the standard error for debugging purpose.
79 void vlc_trace (const char *fn, const char *file, unsigned line)
81 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
82 fflush (stderr); /* needed before switch to low-level I/O */
85 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
86 backtrace_symbols_fd (stack, len, 2);
93 static inline unsigned long vlc_threadid (void)
95 #if defined(LIBVLC_USE_PTHREAD)
96 union { pthread_t th; unsigned long int i; } v = { };
97 v.th = pthread_self ();
100 #elif defined (WIN32)
101 return GetCurrentThreadId ();
109 /*****************************************************************************
110 * vlc_thread_fatal: Report an error from the threading layer
111 *****************************************************************************
112 * This is mostly meant for debugging.
113 *****************************************************************************/
115 vlc_thread_fatal (const char *action, int error,
116 const char *function, const char *file, unsigned line)
118 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
119 action, error, vlc_threadid ());
120 vlc_trace (function, file, line);
122 /* Sometimes strerror_r() crashes too, so make sure we print an error
123 * message before we invoke it */
125 /* Avoid the strerror_r() prototype brain damage in glibc */
127 fprintf (stderr, " Error message: %m at:\n");
128 #elif !defined (WIN32)
132 switch (strerror_r (error, buf, sizeof (buf)))
137 case ERANGE: /* should never happen */
138 msg = "unknwon (too big to display)";
141 msg = "unknown (invalid error number)";
144 fprintf (stderr, " Error message: %s\n", msg);
152 # define VLC_THREAD_ASSERT( action ) \
153 if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
155 # define VLC_THREAD_ASSERT( action ) ((void)val)
159 * Per-thread cancellation data
161 #ifndef LIBVLC_USE_PTHREAD_CANCEL
162 typedef struct vlc_cancel_t
164 vlc_cleanup_t *cleaners;
169 # define VLC_CANCEL_INIT { NULL, true, false }
172 /*****************************************************************************
173 * vlc_threads_init: initialize threads system
174 *****************************************************************************
175 * This function requires lazy initialization of a global lock in order to
176 * keep the library really thread-safe. Some architectures don't support this
177 * and thus do not guarantee the complete reentrancy.
178 *****************************************************************************/
179 int vlc_threads_init( void )
181 int i_ret = VLC_SUCCESS;
183 /* If we have lazy mutex initialization, use it. Otherwise, we just
184 * hope nothing wrong happens. */
185 #if defined( LIBVLC_USE_PTHREAD )
186 pthread_mutex_lock( &once_mutex );
189 if( i_initializations == 0 )
191 p_root = vlc_custom_create( (vlc_object_t *)NULL, sizeof( *p_root ),
192 VLC_OBJECT_GENERIC, "root" );
199 /* We should be safe now. Do all the initialization stuff we want. */
200 #ifndef LIBVLC_USE_PTHREAD_CANCEL
201 vlc_threadvar_create( &cancel_key, free );
207 /* If we have lazy mutex initialization support, unlock the mutex.
208 * Otherwize, we are screwed. */
209 #if defined( LIBVLC_USE_PTHREAD )
210 pthread_mutex_unlock( &once_mutex );
216 /*****************************************************************************
217 * vlc_threads_end: stop threads system
218 *****************************************************************************
219 * FIXME: This function is far from being threadsafe.
220 *****************************************************************************/
221 void vlc_threads_end( void )
223 #if defined( LIBVLC_USE_PTHREAD )
224 pthread_mutex_lock( &once_mutex );
227 assert( i_initializations > 0 );
229 if( i_initializations == 1 )
231 vlc_object_release( p_root );
232 #ifndef LIBVLC_USE_PTHREAD
233 vlc_threadvar_delete( &cancel_key );
238 #if defined( LIBVLC_USE_PTHREAD )
239 pthread_mutex_unlock( &once_mutex );
243 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
244 /* This is not prototyped under glibc, though it exists. */
245 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
248 /*****************************************************************************
249 * vlc_mutex_init: initialize a mutex
250 *****************************************************************************/
251 int vlc_mutex_init( vlc_mutex_t *p_mutex )
253 #if defined( LIBVLC_USE_PTHREAD )
254 pthread_mutexattr_t attr;
257 pthread_mutexattr_init( &attr );
260 /* Create error-checking mutex to detect problems more easily. */
261 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
262 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
264 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
267 i_result = pthread_mutex_init( p_mutex, &attr );
268 pthread_mutexattr_destroy( &attr );
271 #elif defined( WIN32 )
272 InitializeCriticalSection (&p_mutex->mutex);
273 p_mutex->recursive = false;
279 /*****************************************************************************
280 * vlc_mutex_init: initialize a recursive mutex (Do not use)
281 *****************************************************************************/
282 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
284 #if defined( LIBVLC_USE_PTHREAD )
285 pthread_mutexattr_t attr;
288 pthread_mutexattr_init( &attr );
289 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
290 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
292 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
294 i_result = pthread_mutex_init( p_mutex, &attr );
295 pthread_mutexattr_destroy( &attr );
298 #elif defined( WIN32 )
299 InitializeCriticalSection( &p_mutex->mutex );
300 p_mutex->owner = 0; /* the error value for GetThreadId()! */
301 p_mutex->recursion = 0;
302 p_mutex->recursive = true;
310 * Destroys a mutex. The mutex must not be locked.
312 * @param p_mutex mutex to destroy
313 * @return always succeeds
315 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
317 #if defined( LIBVLC_USE_PTHREAD )
318 int val = pthread_mutex_destroy( p_mutex );
319 VLC_THREAD_ASSERT ("destroying mutex");
321 #elif defined( WIN32 )
322 DeleteCriticalSection (&p_mutex->mutex);
328 * Acquires a mutex. If needed, waits for any other thread to release it.
329 * Beware of deadlocks when locking multiple mutexes at the same time,
330 * or when using mutexes from callbacks.
332 * @param p_mutex mutex initialized with vlc_mutex_init() or
333 * vlc_mutex_init_recursive()
335 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
337 #if defined(LIBVLC_USE_PTHREAD)
338 int val = pthread_mutex_lock( p_mutex );
339 VLC_THREAD_ASSERT ("locking mutex");
341 #elif defined( WIN32 )
342 if (p_mutex->recursive)
344 DWORD self = GetCurrentThreadId ();
346 if ((DWORD)InterlockedCompareExchange (&p_mutex->owner, self,
348 { /* We already locked this recursive mutex */
349 p_mutex->recursion++;
353 /* We need to lock this recursive mutex */
354 EnterCriticalSection (&p_mutex->mutex);
355 self = InterlockedCompareExchange (&p_mutex->owner, self, 0);
356 assert (self == 0); /* no previous owner */
359 /* Non-recursive mutex */
360 EnterCriticalSection (&p_mutex->mutex);
367 * Releases a mutex (or crashes if the mutex is not locked by the caller).
368 * @param p_mutex mutex locked with vlc_mutex_lock().
370 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
372 #if defined(LIBVLC_USE_PTHREAD)
373 int val = pthread_mutex_unlock( p_mutex );
374 VLC_THREAD_ASSERT ("unlocking mutex");
376 #elif defined( WIN32 )
377 if (p_mutex->recursive)
379 if (--p_mutex->recursion != 0)
380 return; /* We still own this mutex */
382 /* We release the mutex */
383 DWORD self = GetCurrentThreadId ();
384 self = InterlockedCompareExchange (&p_mutex->owner, self, 0);
385 assert (self == GetCurrentThreadId ());
388 LeaveCriticalSection (&p_mutex->mutex);
393 /*****************************************************************************
394 * vlc_cond_init: initialize a condition variable
395 *****************************************************************************/
396 int vlc_cond_init( vlc_cond_t *p_condvar )
398 #if defined( LIBVLC_USE_PTHREAD )
399 pthread_condattr_t attr;
402 ret = pthread_condattr_init (&attr);
406 # if !defined (_POSIX_CLOCK_SELECTION)
407 /* Fairly outdated POSIX support (that was defined in 2001) */
408 # define _POSIX_CLOCK_SELECTION (-1)
410 # if (_POSIX_CLOCK_SELECTION >= 0)
411 /* NOTE: This must be the same clock as the one in mtime.c */
412 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
415 ret = pthread_cond_init (p_condvar, &attr);
416 pthread_condattr_destroy (&attr);
419 #elif defined( WIN32 )
420 /* Create a manual-reset event (manual reset is needed for broadcast). */
421 *p_condvar = CreateEvent( NULL, TRUE, FALSE, NULL );
422 return *p_condvar ? 0 : ENOMEM;
428 * Destroys a condition variable. No threads shall be waiting or signaling the
430 * @param p_condvar condition variable to destroy
432 void vlc_cond_destroy (vlc_cond_t *p_condvar)
434 #if defined( LIBVLC_USE_PTHREAD )
435 int val = pthread_cond_destroy( p_condvar );
436 VLC_THREAD_ASSERT ("destroying condition");
438 #elif defined( WIN32 )
439 CloseHandle( *p_condvar );
445 * Wakes up one thread waiting on a condition variable, if any.
446 * @param p_condvar condition variable
448 void vlc_cond_signal (vlc_cond_t *p_condvar)
450 #if defined(LIBVLC_USE_PTHREAD)
451 int val = pthread_cond_signal( p_condvar );
452 VLC_THREAD_ASSERT ("signaling condition variable");
454 #elif defined( WIN32 )
455 /* NOTE: This will cause a broadcast, that is wrong.
456 * This will also wake up the next waiting thread if no thread are yet
457 * waiting, which is also wrong. However both of these issues are allowed
458 * by the provision for spurious wakeups. Better have too many wakeups
459 * than too few (= deadlocks). */
460 SetEvent (*p_condvar);
466 * Wakes up all threads (if any) waiting on a condition variable.
467 * @param p_cond condition variable
469 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
471 #if defined (LIBVLC_USE_PTHREAD)
472 pthread_cond_broadcast (p_condvar);
474 #elif defined (WIN32)
475 SetEvent (*p_condvar);
482 # define WaitForMultipleObjectsEx(a,b,c) WaitForMultipleObjects(a,b)
486 * Waits for a condition variable. The calling thread will be suspended until
487 * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
488 * condition variable, the thread is cancelled with vlc_cancel(), or the
489 * system causes a "spurious" unsolicited wake-up.
491 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
492 * a recursive mutex. Although it is possible to use the same mutex for
493 * multiple condition, it is not valid to use different mutexes for the same
494 * condition variable at the same time from different threads.
496 * In case of thread cancellation, the mutex is always locked before
497 * cancellation proceeds.
499 * The canonical way to use a condition variable to wait for event foobar is:
501 vlc_mutex_lock (&lock);
502 mutex_cleanup_push (&lock); // release the mutex in case of cancellation
505 vlc_cond_wait (&wait, &lock);
507 --- foobar is now true, do something about it here --
509 vlc_cleanup_run (); // release the mutex
512 * @param p_condvar condition variable to wait on
513 * @param p_mutex mutex which is unlocked while waiting,
514 * then locked again when waking up.
515 * @param deadline <b>absolute</b> timeout
517 * @return 0 if the condition was signaled, an error code in case of timeout.
519 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
521 #if defined(LIBVLC_USE_PTHREAD)
522 int val = pthread_cond_wait( p_condvar, p_mutex );
523 VLC_THREAD_ASSERT ("waiting on condition");
525 #elif defined( WIN32 )
530 LeaveCriticalSection (&p_mutex->mutex);
531 result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
532 EnterCriticalSection (&p_mutex->mutex);
534 while (result == WAIT_IO_COMPLETION);
540 * Waits for a condition variable up to a certain date.
541 * This works like vlc_cond_wait(), except for the additional timeout.
543 * @param p_condvar condition variable to wait on
544 * @param p_mutex mutex which is unlocked while waiting,
545 * then locked again when waking up.
546 * @param deadline <b>absolute</b> timeout
548 * @return 0 if the condition was signaled, an error code in case of timeout.
550 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
553 #if defined(LIBVLC_USE_PTHREAD)
554 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
555 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
557 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
558 if (val != ETIMEDOUT)
559 VLC_THREAD_ASSERT ("timed-waiting on condition");
562 #elif defined( WIN32 )
569 mtime_t total = (deadline - mdate ())/1000;
573 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
574 LeaveCriticalSection (&p_mutex->mutex);
575 result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
576 EnterCriticalSection (&p_mutex->mutex);
578 while (result == WAIT_IO_COMPLETION);
580 return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
585 /*****************************************************************************
586 * vlc_tls_create: create a thread-local variable
587 *****************************************************************************/
588 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
592 #if defined( LIBVLC_USE_PTHREAD )
593 i_ret = pthread_key_create( p_tls, destr );
594 #elif defined( UNDER_CE )
596 #elif defined( WIN32 )
597 /* FIXME: remember/use the destr() callback and stop leaking whatever */
599 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
601 # error Unimplemented!
606 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
608 #if defined( LIBVLC_USE_PTHREAD )
609 pthread_key_delete (*p_tls);
610 #elif defined( UNDER_CE )
611 #elif defined( WIN32 )
614 # error Unimplemented!
618 #if defined (LIBVLC_USE_PTHREAD)
619 #elif defined (WIN32)
620 static unsigned __stdcall vlc_entry (void *data)
622 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
623 vlc_thread_t self = data;
625 vlc_threadvar_set (&cancel_key, &cancel_data);
626 self->data = self->entry (self->data);
632 * Creates and starts new thread.
634 * @param p_handle [OUT] pointer to write the handle of the created thread to
635 * @param entry entry point for the thread
636 * @param data data parameter given to the entry point
637 * @param priority thread priority value
638 * @return 0 on success, a standard error code on error.
640 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
645 #if defined( LIBVLC_USE_PTHREAD )
647 pthread_attr_init (&attr);
649 /* Block the signals that signals interface plugin handles.
650 * If the LibVLC caller wants to handle some signals by itself, it should
651 * block these before whenever invoking LibVLC. And it must obviously not
652 * start the VLC signals interface plugin.
654 * LibVLC will normally ignore any interruption caused by an asynchronous
655 * signal during a system call. But there may well be some buggy cases
656 * where it fails to handle EINTR (bug reports welcome). Some underlying
657 * libraries might also not handle EINTR properly.
663 sigdelset (&set, SIGHUP);
664 sigaddset (&set, SIGINT);
665 sigaddset (&set, SIGQUIT);
666 sigaddset (&set, SIGTERM);
668 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
669 pthread_sigmask (SIG_BLOCK, &set, &oldset);
672 struct sched_param sp = { .sched_priority = priority, };
675 if (sp.sched_priority <= 0)
676 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
678 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
680 pthread_attr_setschedpolicy (&attr, policy);
681 pthread_attr_setschedparam (&attr, &sp);
684 ret = pthread_create (p_handle, &attr, entry, data);
685 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
686 pthread_attr_destroy (&attr);
688 #elif defined( WIN32 ) || defined( UNDER_CE )
689 /* When using the MSVCRT C library you have to use the _beginthreadex
690 * function instead of CreateThread, otherwise you'll end up with
691 * memory leaks and the signal functions not working (see Microsoft
692 * Knowledge Base, article 104641) */
694 vlc_thread_t th = malloc (sizeof (*th));
701 #if defined( UNDER_CE )
702 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
704 hThread = (HANDLE)(uintptr_t)
705 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
710 /* Thread closes the handle when exiting, duplicate it here
711 * to be on the safe side when joining. */
712 if (!DuplicateHandle (GetCurrentProcess (), hThread,
713 GetCurrentProcess (), &th->handle, 0, FALSE,
714 DUPLICATE_SAME_ACCESS))
716 CloseHandle (hThread);
721 ResumeThread (hThread);
723 SetThreadPriority (hThread, priority);
739 /* APC procedure for thread cancellation */
740 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
743 vlc_control_cancel (VLC_DO_CANCEL);
748 * Marks a thread as cancelled. Next time the target thread reaches a
749 * cancellation point (while not having disabled cancellation), it will
750 * run its cancellation cleanup handler, the thread variable destructors, and
751 * terminate. vlc_join() must be used afterward regardless of a thread being
754 void vlc_cancel (vlc_thread_t thread_id)
756 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
757 pthread_cancel (thread_id);
758 #elif defined (WIN32)
759 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
761 # warning vlc_cancel is not implemented!
766 * Waits for a thread to complete (if needed), and destroys it.
767 * This is a cancellation point; in case of cancellation, the join does _not_
770 * @param handle thread handle
771 * @param p_result [OUT] pointer to write the thread return value or NULL
772 * @return 0 on success, a standard error code otherwise.
774 void vlc_join (vlc_thread_t handle, void **result)
776 #if defined( LIBVLC_USE_PTHREAD )
777 int val = pthread_join (handle, result);
779 vlc_thread_fatal ("joining thread", val, __func__, __FILE__, __LINE__);
781 #elif defined( UNDER_CE ) || defined( WIN32 )
784 while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
785 == WAIT_IO_COMPLETION);
787 CloseHandle (handle->handle);
789 *result = handle->data;
796 struct vlc_thread_boot
798 void * (*entry) (vlc_object_t *);
799 vlc_object_t *object;
802 static void *thread_entry (void *data)
804 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
805 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
808 msg_Dbg (obj, "thread started");
810 msg_Dbg (obj, "thread ended");
815 /*****************************************************************************
816 * vlc_thread_create: create a thread, inner version
817 *****************************************************************************
818 * Note that i_priority is only taken into account on platforms supporting
819 * userland real-time priority threads.
820 *****************************************************************************/
821 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
822 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
823 int i_priority, bool b_wait )
826 vlc_object_internals_t *p_priv = vlc_internals( p_this );
828 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
832 boot->object = p_this;
834 vlc_object_lock( p_this );
836 /* Make sure we don't re-create a thread if the object has already one */
837 assert( !p_priv->b_thread );
839 #if defined( LIBVLC_USE_PTHREAD )
841 if( config_GetInt( p_this, "rt-priority" ) > 0 )
844 /* Hack to avoid error msg */
845 if( config_GetType( p_this, "rt-offset" ) )
846 i_priority += config_GetInt( p_this, "rt-offset" );
850 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
855 msg_Dbg( p_this, "waiting for thread initialization" );
856 vlc_object_wait( p_this );
859 p_priv->b_thread = true;
860 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
861 (unsigned long)p_priv->thread_id, psz_name, i_priority,
867 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
868 psz_name, psz_file, i_line );
871 vlc_object_unlock( p_this );
875 /*****************************************************************************
876 * vlc_thread_set_priority: set the priority of the current thread when we
877 * couldn't set it in vlc_thread_create (for instance for the main thread)
878 *****************************************************************************/
879 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
880 int i_line, int i_priority )
882 vlc_object_internals_t *p_priv = vlc_internals( p_this );
884 if( !p_priv->b_thread )
886 msg_Err( p_this, "couldn't set priority of non-existent thread" );
890 #if defined( LIBVLC_USE_PTHREAD )
892 if( config_GetInt( p_this, "rt-priority" ) > 0 )
895 int i_error, i_policy;
896 struct sched_param param;
898 memset( ¶m, 0, sizeof(struct sched_param) );
899 if( config_GetType( p_this, "rt-offset" ) )
900 i_priority += config_GetInt( p_this, "rt-offset" );
901 if( i_priority <= 0 )
903 param.sched_priority = (-1) * i_priority;
904 i_policy = SCHED_OTHER;
908 param.sched_priority = i_priority;
911 if( (i_error = pthread_setschedparam( p_priv->thread_id,
912 i_policy, ¶m )) )
915 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
921 #elif defined( WIN32 ) || defined( UNDER_CE )
922 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
924 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
926 msg_Warn( p_this, "couldn't set a faster priority" );
935 /*****************************************************************************
936 * vlc_thread_join: wait until a thread exits, inner version
937 *****************************************************************************/
938 void __vlc_thread_join( vlc_object_t *p_this )
940 vlc_object_internals_t *p_priv = vlc_internals( p_this );
942 #if defined( LIBVLC_USE_PTHREAD )
943 vlc_join (p_priv->thread_id, NULL);
945 #elif defined( UNDER_CE ) || defined( WIN32 )
947 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
948 int64_t real_time, kernel_time, user_time;
950 if( ! DuplicateHandle(GetCurrentProcess(),
951 p_priv->thread_id->handle,
956 DUPLICATE_SAME_ACCESS) )
958 p_priv->b_thread = false;
959 return; /* We have a problem! */
962 vlc_join( p_priv->thread_id, NULL );
964 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
967 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
968 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
972 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
973 kernel_ft.dwLowDateTime) / 10;
976 ((((int64_t)user_ft.dwHighDateTime)<<32)|
977 user_ft.dwLowDateTime) / 10;
979 msg_Dbg( p_this, "thread times: "
980 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
981 real_time/60/1000000,
982 (double)((real_time%(60*1000000))/1000000.0),
983 kernel_time/60/1000000,
984 (double)((kernel_time%(60*1000000))/1000000.0),
985 user_time/60/1000000,
986 (double)((user_time%(60*1000000))/1000000.0) );
988 CloseHandle( hThread );
991 vlc_join( p_priv->thread_id, NULL );
995 p_priv->b_thread = false;
998 void vlc_thread_cancel (vlc_object_t *obj)
1000 vlc_object_internals_t *priv = vlc_internals (obj);
1003 vlc_cancel (priv->thread_id);
1006 void vlc_control_cancel (int cmd, ...)
1008 /* NOTE: This function only modifies thread-specific data, so there is no
1009 * need to lock anything. */
1010 #ifdef LIBVLC_USE_PTHREAD_CANCEL
1016 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
1020 /* Main thread - cannot be cancelled anyway */
1023 nfo = malloc (sizeof (*nfo));
1025 return; /* Uho! Expect problems! */
1026 *nfo = VLC_CANCEL_INIT;
1027 vlc_threadvar_set (&cancel_key, nfo);
1034 case VLC_SAVE_CANCEL:
1036 int *p_state = va_arg (ap, int *);
1037 *p_state = nfo->killable;
1038 nfo->killable = false;
1042 case VLC_RESTORE_CANCEL:
1044 int state = va_arg (ap, int);
1045 nfo->killable = state != 0;
1049 case VLC_TEST_CANCEL:
1050 if (nfo->killable && nfo->killed)
1052 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
1055 #if defined (LIBVLC_USE_PTHREAD)
1056 pthread_exit (PTHREAD_CANCELLED);
1057 #elif defined (WIN32)
1060 # error Not implemented!
1069 case VLC_CLEANUP_PUSH:
1071 /* cleaner is a pointer to the caller stack, no need to allocate
1072 * and copy anything. As a nice side effect, this cannot fail. */
1073 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
1074 cleaner->next = nfo->cleaners;
1075 nfo->cleaners = cleaner;
1079 case VLC_CLEANUP_POP:
1081 nfo->cleaners = nfo->cleaners->next;