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 vlc_object_t *vlc_global( void )
64 assert( i_initializations > 0 );
68 #ifdef HAVE_EXECINFO_H
69 # include <execinfo.h>
73 * Print a backtrace to the standard error for debugging purpose.
75 void vlc_trace (const char *fn, const char *file, unsigned line)
77 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
78 fflush (stderr); /* needed before switch to low-level I/O */
81 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
82 backtrace_symbols_fd (stack, len, 2);
89 static inline unsigned long vlc_threadid (void)
91 #if defined(LIBVLC_USE_PTHREAD)
92 union { pthread_t th; unsigned long int i; } v = { };
93 v.th = pthread_self ();
97 return GetCurrentThreadId ();
105 /*****************************************************************************
106 * vlc_thread_fatal: Report an error from the threading layer
107 *****************************************************************************
108 * This is mostly meant for debugging.
109 *****************************************************************************/
111 vlc_thread_fatal (const char *action, int error,
112 const char *function, const char *file, unsigned line)
114 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
115 action, error, vlc_threadid ());
116 vlc_trace (function, file, line);
118 /* Sometimes strerror_r() crashes too, so make sure we print an error
119 * message before we invoke it */
121 /* Avoid the strerror_r() prototype brain damage in glibc */
123 fprintf (stderr, " Error message: %m\n");
124 #elif !defined (WIN32)
128 switch (strerror_r (error, buf, sizeof (buf)))
133 case ERANGE: /* should never happen */
134 msg = "unknwon (too big to display)";
137 msg = "unknown (invalid error number)";
140 fprintf (stderr, " Error message: %s\n", msg);
148 # define VLC_THREAD_ASSERT( action ) \
149 if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
151 # define VLC_THREAD_ASSERT( action ) ((void)val)
155 * Per-thread cancellation data
157 #ifndef LIBVLC_USE_PTHREAD_CANCEL
158 typedef struct vlc_cancel_t
160 vlc_cleanup_t *cleaners;
165 # define VLC_CANCEL_INIT { NULL, true, false }
168 /*****************************************************************************
169 * vlc_threads_init: initialize threads system
170 *****************************************************************************
171 * This function requires lazy initialization of a global lock in order to
172 * keep the library really thread-safe. Some architectures don't support this
173 * and thus do not guarantee the complete reentrancy.
174 *****************************************************************************/
175 int vlc_threads_init( void )
177 int i_ret = VLC_SUCCESS;
179 /* If we have lazy mutex initialization, use it. Otherwise, we just
180 * hope nothing wrong happens. */
181 #if defined( LIBVLC_USE_PTHREAD )
182 pthread_mutex_lock( &once_mutex );
185 if( i_initializations == 0 )
187 p_root = vlc_custom_create( (vlc_object_t *)NULL, sizeof( *p_root ),
188 VLC_OBJECT_GENERIC, "root" );
195 /* We should be safe now. Do all the initialization stuff we want. */
196 #ifndef LIBVLC_USE_PTHREAD_CANCEL
197 vlc_threadvar_create( &cancel_key, free );
203 /* If we have lazy mutex initialization support, unlock the mutex.
204 * Otherwize, we are screwed. */
205 #if defined( LIBVLC_USE_PTHREAD )
206 pthread_mutex_unlock( &once_mutex );
212 /*****************************************************************************
213 * vlc_threads_end: stop threads system
214 *****************************************************************************
215 * FIXME: This function is far from being threadsafe.
216 *****************************************************************************/
217 void vlc_threads_end( void )
219 #if defined( LIBVLC_USE_PTHREAD )
220 pthread_mutex_lock( &once_mutex );
223 assert( i_initializations > 0 );
225 if( i_initializations == 1 )
227 vlc_object_release( p_root );
228 #ifndef LIBVLC_USE_PTHREAD
229 vlc_threadvar_delete( &cancel_key );
234 #if defined( LIBVLC_USE_PTHREAD )
235 pthread_mutex_unlock( &once_mutex );
239 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
240 /* This is not prototyped under glibc, though it exists. */
241 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
244 /*****************************************************************************
245 * vlc_mutex_init: initialize a mutex
246 *****************************************************************************/
247 int vlc_mutex_init( vlc_mutex_t *p_mutex )
249 #if defined( LIBVLC_USE_PTHREAD )
250 pthread_mutexattr_t attr;
253 pthread_mutexattr_init( &attr );
256 /* Create error-checking mutex to detect problems more easily. */
257 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
258 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
260 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
263 i_result = pthread_mutex_init( p_mutex, &attr );
264 pthread_mutexattr_destroy( &attr );
267 #elif defined( WIN32 )
268 InitializeCriticalSection (&p_mutex->mutex);
269 p_mutex->recursive = false;
275 /*****************************************************************************
276 * vlc_mutex_init: initialize a recursive mutex (Do not use)
277 *****************************************************************************/
278 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
280 #if defined( LIBVLC_USE_PTHREAD )
281 pthread_mutexattr_t attr;
284 pthread_mutexattr_init( &attr );
285 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
286 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
288 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
290 i_result = pthread_mutex_init( p_mutex, &attr );
291 pthread_mutexattr_destroy( &attr );
294 #elif defined( WIN32 )
295 InitializeCriticalSection( &p_mutex->mutex );
296 p_mutex->owner = 0; /* the error value for GetThreadId()! */
297 p_mutex->recursion = 0;
298 p_mutex->recursive = true;
306 * Destroys a mutex. The mutex must not be locked.
308 * @param p_mutex mutex to destroy
309 * @return always succeeds
311 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
313 #if defined( LIBVLC_USE_PTHREAD )
314 int val = pthread_mutex_destroy( p_mutex );
315 VLC_THREAD_ASSERT ("destroying mutex");
317 #elif defined( WIN32 )
318 DeleteCriticalSection (&p_mutex->mutex);
324 * Acquires a mutex. If needed, waits for any other thread to release it.
325 * Beware of deadlocks when locking multiple mutexes at the same time,
326 * or when using mutexes from callbacks.
328 * @param p_mutex mutex initialized with vlc_mutex_init() or
329 * vlc_mutex_init_recursive()
331 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
333 #if defined(LIBVLC_USE_PTHREAD)
334 int val = pthread_mutex_lock( p_mutex );
335 VLC_THREAD_ASSERT ("locking mutex");
337 #elif defined( WIN32 )
338 if (p_mutex->recursive)
340 DWORD self = GetCurrentThreadId ();
342 if ((DWORD)InterlockedCompareExchange (&p_mutex->owner, self,
344 { /* We already locked this recursive mutex */
345 p_mutex->recursion++;
349 /* We need to lock this recursive mutex */
350 EnterCriticalSection (&p_mutex->mutex);
351 self = InterlockedExchange (&p_mutex->owner, self);
352 assert (self == 0); /* no previous owner */
355 /* Non-recursive mutex */
356 EnterCriticalSection (&p_mutex->mutex);
363 * Releases a mutex (or crashes if the mutex is not locked by the caller).
364 * @param p_mutex mutex locked with vlc_mutex_lock().
366 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
368 #if defined(LIBVLC_USE_PTHREAD)
369 int val = pthread_mutex_unlock( p_mutex );
370 VLC_THREAD_ASSERT ("unlocking mutex");
372 #elif defined( WIN32 )
373 if (p_mutex->recursive)
375 if (p_mutex->recursion != 0)
377 p_mutex->recursion--;
378 return; /* We still own this mutex */
381 /* We release the mutex */
382 InterlockedExchange (&p_mutex->owner, 0);
385 LeaveCriticalSection (&p_mutex->mutex);
390 /*****************************************************************************
391 * vlc_cond_init: initialize a condition variable
392 *****************************************************************************/
393 int vlc_cond_init( vlc_cond_t *p_condvar )
395 #if defined( LIBVLC_USE_PTHREAD )
396 pthread_condattr_t attr;
399 ret = pthread_condattr_init (&attr);
403 # if !defined (_POSIX_CLOCK_SELECTION)
404 /* Fairly outdated POSIX support (that was defined in 2001) */
405 # define _POSIX_CLOCK_SELECTION (-1)
407 # if (_POSIX_CLOCK_SELECTION >= 0)
408 /* NOTE: This must be the same clock as the one in mtime.c */
409 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
412 ret = pthread_cond_init (p_condvar, &attr);
413 pthread_condattr_destroy (&attr);
416 #elif defined( WIN32 )
417 /* Create a manual-reset event (manual reset is needed for broadcast). */
418 *p_condvar = CreateEvent( NULL, TRUE, FALSE, NULL );
419 return *p_condvar ? 0 : ENOMEM;
425 * Destroys a condition variable. No threads shall be waiting or signaling the
427 * @param p_condvar condition variable to destroy
429 void vlc_cond_destroy (vlc_cond_t *p_condvar)
431 #if defined( LIBVLC_USE_PTHREAD )
432 int val = pthread_cond_destroy( p_condvar );
433 VLC_THREAD_ASSERT ("destroying condition");
435 #elif defined( WIN32 )
436 CloseHandle( *p_condvar );
442 * Wakes up one thread waiting on a condition variable, if any.
443 * @param p_condvar condition variable
445 void vlc_cond_signal (vlc_cond_t *p_condvar)
447 #if defined(LIBVLC_USE_PTHREAD)
448 int val = pthread_cond_signal( p_condvar );
449 VLC_THREAD_ASSERT ("signaling condition variable");
451 #elif defined( WIN32 )
452 /* NOTE: This will cause a broadcast, that is wrong.
453 * This will also wake up the next waiting thread if no thread are yet
454 * waiting, which is also wrong. However both of these issues are allowed
455 * by the provision for spurious wakeups. Better have too many wakeups
456 * than too few (= deadlocks). */
457 SetEvent (*p_condvar);
463 * Wakes up all threads (if any) waiting on a condition variable.
464 * @param p_cond condition variable
466 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
468 #if defined (LIBVLC_USE_PTHREAD)
469 pthread_cond_broadcast (p_condvar);
471 #elif defined (WIN32)
472 SetEvent (*p_condvar);
479 # define WaitForMultipleObjectsEx(a,b,c) WaitForMultipleObjects(a,b)
483 * Waits for a condition variable. The calling thread will be suspended until
484 * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
485 * condition variable, the thread is cancelled with vlc_cancel(), or the
486 * system causes a "spurious" unsolicited wake-up.
488 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
489 * a recursive mutex. Although it is possible to use the same mutex for
490 * multiple condition, it is not valid to use different mutexes for the same
491 * condition variable at the same time from different threads.
493 * In case of thread cancellation, the mutex is always locked before
494 * cancellation proceeds.
496 * The canonical way to use a condition variable to wait for event foobar is:
498 vlc_mutex_lock (&lock);
499 mutex_cleanup_push (&lock); // release the mutex in case of cancellation
502 vlc_cond_wait (&wait, &lock);
504 --- foobar is now true, do something about it here --
506 vlc_cleanup_run (); // release the mutex
509 * @param p_condvar condition variable to wait on
510 * @param p_mutex mutex which is unlocked while waiting,
511 * then locked again when waking up.
512 * @param deadline <b>absolute</b> timeout
514 * @return 0 if the condition was signaled, an error code in case of timeout.
516 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
518 #if defined(LIBVLC_USE_PTHREAD)
519 int val = pthread_cond_wait( p_condvar, p_mutex );
520 VLC_THREAD_ASSERT ("waiting on condition");
522 #elif defined( WIN32 )
525 assert (!p_mutex->recursive);
529 LeaveCriticalSection (&p_mutex->mutex);
530 result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
531 EnterCriticalSection (&p_mutex->mutex);
533 while (result == WAIT_IO_COMPLETION);
535 ResetEvent (*p_condvar);
541 * Waits for a condition variable up to a certain date.
542 * This works like vlc_cond_wait(), except for the additional timeout.
544 * @param p_condvar condition variable to wait on
545 * @param p_mutex mutex which is unlocked while waiting,
546 * then locked again when waking up.
547 * @param deadline <b>absolute</b> timeout
549 * @return 0 if the condition was signaled, an error code in case of timeout.
551 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
554 #if defined(LIBVLC_USE_PTHREAD)
555 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
556 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
558 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
559 if (val != ETIMEDOUT)
560 VLC_THREAD_ASSERT ("timed-waiting on condition");
563 #elif defined( WIN32 )
566 assert (!p_mutex->recursive);
571 mtime_t total = (deadline - mdate ())/1000;
575 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
576 LeaveCriticalSection (&p_mutex->mutex);
577 result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
578 EnterCriticalSection (&p_mutex->mutex);
580 while (result == WAIT_IO_COMPLETION);
582 ResetEvent (*p_condvar);
584 return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
589 /*****************************************************************************
590 * vlc_tls_create: create a thread-local variable
591 *****************************************************************************/
592 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
596 #if defined( LIBVLC_USE_PTHREAD )
597 i_ret = pthread_key_create( p_tls, destr );
598 #elif defined( UNDER_CE )
600 #elif defined( WIN32 )
601 /* FIXME: remember/use the destr() callback and stop leaking whatever */
603 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
605 # error Unimplemented!
610 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
612 #if defined( LIBVLC_USE_PTHREAD )
613 pthread_key_delete (*p_tls);
614 #elif defined( UNDER_CE )
615 #elif defined( WIN32 )
618 # error Unimplemented!
622 #if defined (LIBVLC_USE_PTHREAD)
623 #elif defined (WIN32)
624 static unsigned __stdcall vlc_entry (void *data)
626 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
627 vlc_thread_t self = data;
629 vlc_threadvar_set (&cancel_key, &cancel_data);
630 self->data = self->entry (self->data);
636 * Creates and starts new thread.
638 * @param p_handle [OUT] pointer to write the handle of the created thread to
639 * @param entry entry point for the thread
640 * @param data data parameter given to the entry point
641 * @param priority thread priority value
642 * @return 0 on success, a standard error code on error.
644 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
649 #if defined( LIBVLC_USE_PTHREAD )
651 pthread_attr_init (&attr);
653 /* Block the signals that signals interface plugin handles.
654 * If the LibVLC caller wants to handle some signals by itself, it should
655 * block these before whenever invoking LibVLC. And it must obviously not
656 * start the VLC signals interface plugin.
658 * LibVLC will normally ignore any interruption caused by an asynchronous
659 * signal during a system call. But there may well be some buggy cases
660 * where it fails to handle EINTR (bug reports welcome). Some underlying
661 * libraries might also not handle EINTR properly.
667 sigdelset (&set, SIGHUP);
668 sigaddset (&set, SIGINT);
669 sigaddset (&set, SIGQUIT);
670 sigaddset (&set, SIGTERM);
672 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
673 pthread_sigmask (SIG_BLOCK, &set, &oldset);
676 struct sched_param sp = { .sched_priority = priority, };
679 if (sp.sched_priority <= 0)
680 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
682 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
684 pthread_attr_setschedpolicy (&attr, policy);
685 pthread_attr_setschedparam (&attr, &sp);
688 /* The thread stack size.
689 * The lower the value, the less address space per thread, the highest
690 * maximum simultaneous threads per process. Too low values will cause
691 * stack overflows and weird crashes. Set with caution. Also keep in mind
692 * that 64-bits platforms consume more stack than 32-bits one.
694 * Thanks to on-demand paging, thread stack size only affects address space
695 * consumption. In terms of memory, threads only use what they need
696 * (rounded up to the page boundary).
698 * For example, on Linux i386, the default is 2 mega-bytes, which supports
699 * about 320 threads per processes. */
700 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
703 ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
704 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
707 ret = pthread_create (p_handle, &attr, entry, data);
708 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
709 pthread_attr_destroy (&attr);
711 #elif defined( WIN32 ) || defined( UNDER_CE )
712 /* When using the MSVCRT C library you have to use the _beginthreadex
713 * function instead of CreateThread, otherwise you'll end up with
714 * memory leaks and the signal functions not working (see Microsoft
715 * Knowledge Base, article 104641) */
717 vlc_thread_t th = malloc (sizeof (*th));
724 #if defined( UNDER_CE )
725 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
727 hThread = (HANDLE)(uintptr_t)
728 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
733 /* Thread closes the handle when exiting, duplicate it here
734 * to be on the safe side when joining. */
735 if (!DuplicateHandle (GetCurrentProcess (), hThread,
736 GetCurrentProcess (), &th->handle, 0, FALSE,
737 DUPLICATE_SAME_ACCESS))
739 CloseHandle (hThread);
744 ResumeThread (hThread);
746 SetThreadPriority (hThread, priority);
762 /* APC procedure for thread cancellation */
763 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
766 vlc_control_cancel (VLC_DO_CANCEL);
771 * Marks a thread as cancelled. Next time the target thread reaches a
772 * cancellation point (while not having disabled cancellation), it will
773 * run its cancellation cleanup handler, the thread variable destructors, and
774 * terminate. vlc_join() must be used afterward regardless of a thread being
777 void vlc_cancel (vlc_thread_t thread_id)
779 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
780 pthread_cancel (thread_id);
781 #elif defined (WIN32)
782 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
784 # warning vlc_cancel is not implemented!
789 * Waits for a thread to complete (if needed), and destroys it.
790 * This is a cancellation point; in case of cancellation, the join does _not_
793 * @param handle thread handle
794 * @param p_result [OUT] pointer to write the thread return value or NULL
795 * @return 0 on success, a standard error code otherwise.
797 void vlc_join (vlc_thread_t handle, void **result)
799 #if defined( LIBVLC_USE_PTHREAD )
800 int val = pthread_join (handle, result);
802 vlc_thread_fatal ("joining thread", val, __func__, __FILE__, __LINE__);
804 #elif defined( UNDER_CE ) || defined( WIN32 )
807 while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
808 == WAIT_IO_COMPLETION);
810 CloseHandle (handle->handle);
812 *result = handle->data;
819 struct vlc_thread_boot
821 void * (*entry) (vlc_object_t *);
822 vlc_object_t *object;
825 static void *thread_entry (void *data)
827 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
828 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
831 msg_Dbg (obj, "thread started");
833 msg_Dbg (obj, "thread ended");
838 /*****************************************************************************
839 * vlc_thread_create: create a thread, inner version
840 *****************************************************************************
841 * Note that i_priority is only taken into account on platforms supporting
842 * userland real-time priority threads.
843 *****************************************************************************/
844 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
845 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
846 int i_priority, bool b_wait )
849 vlc_object_internals_t *p_priv = vlc_internals( p_this );
851 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
855 boot->object = p_this;
857 vlc_object_lock( p_this );
859 /* Make sure we don't re-create a thread if the object has already one */
860 assert( !p_priv->b_thread );
862 #if defined( LIBVLC_USE_PTHREAD )
864 if( config_GetInt( p_this, "rt-priority" ) > 0 )
867 /* Hack to avoid error msg */
868 if( config_GetType( p_this, "rt-offset" ) )
869 i_priority += config_GetInt( p_this, "rt-offset" );
873 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
878 msg_Dbg( p_this, "waiting for thread initialization" );
879 vlc_object_wait( p_this );
882 p_priv->b_thread = true;
883 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
884 (unsigned long)p_priv->thread_id, psz_name, i_priority,
890 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
891 psz_name, psz_file, i_line );
894 vlc_object_unlock( p_this );
898 /*****************************************************************************
899 * vlc_thread_set_priority: set the priority of the current thread when we
900 * couldn't set it in vlc_thread_create (for instance for the main thread)
901 *****************************************************************************/
902 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
903 int i_line, int i_priority )
905 vlc_object_internals_t *p_priv = vlc_internals( p_this );
907 if( !p_priv->b_thread )
909 msg_Err( p_this, "couldn't set priority of non-existent thread" );
913 #if defined( LIBVLC_USE_PTHREAD )
915 if( config_GetInt( p_this, "rt-priority" ) > 0 )
918 int i_error, i_policy;
919 struct sched_param param;
921 memset( ¶m, 0, sizeof(struct sched_param) );
922 if( config_GetType( p_this, "rt-offset" ) )
923 i_priority += config_GetInt( p_this, "rt-offset" );
924 if( i_priority <= 0 )
926 param.sched_priority = (-1) * i_priority;
927 i_policy = SCHED_OTHER;
931 param.sched_priority = i_priority;
934 if( (i_error = pthread_setschedparam( p_priv->thread_id,
935 i_policy, ¶m )) )
938 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
944 #elif defined( WIN32 ) || defined( UNDER_CE )
945 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
947 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
949 msg_Warn( p_this, "couldn't set a faster priority" );
958 /*****************************************************************************
959 * vlc_thread_join: wait until a thread exits, inner version
960 *****************************************************************************/
961 void __vlc_thread_join( vlc_object_t *p_this )
963 vlc_object_internals_t *p_priv = vlc_internals( p_this );
965 #if defined( LIBVLC_USE_PTHREAD )
966 vlc_join (p_priv->thread_id, NULL);
968 #elif defined( UNDER_CE ) || defined( WIN32 )
970 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
971 int64_t real_time, kernel_time, user_time;
973 if( ! DuplicateHandle(GetCurrentProcess(),
974 p_priv->thread_id->handle,
979 DUPLICATE_SAME_ACCESS) )
981 p_priv->b_thread = false;
982 return; /* We have a problem! */
985 vlc_join( p_priv->thread_id, NULL );
987 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
990 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
991 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
995 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
996 kernel_ft.dwLowDateTime) / 10;
999 ((((int64_t)user_ft.dwHighDateTime)<<32)|
1000 user_ft.dwLowDateTime) / 10;
1002 msg_Dbg( p_this, "thread times: "
1003 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
1004 real_time/60/1000000,
1005 (double)((real_time%(60*1000000))/1000000.0),
1006 kernel_time/60/1000000,
1007 (double)((kernel_time%(60*1000000))/1000000.0),
1008 user_time/60/1000000,
1009 (double)((user_time%(60*1000000))/1000000.0) );
1011 CloseHandle( hThread );
1014 vlc_join( p_priv->thread_id, NULL );
1018 p_priv->b_thread = false;
1021 void vlc_thread_cancel (vlc_object_t *obj)
1023 vlc_object_internals_t *priv = vlc_internals (obj);
1026 vlc_cancel (priv->thread_id);
1029 void vlc_control_cancel (int cmd, ...)
1031 /* NOTE: This function only modifies thread-specific data, so there is no
1032 * need to lock anything. */
1033 #ifdef LIBVLC_USE_PTHREAD_CANCEL
1039 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
1043 /* Main thread - cannot be cancelled anyway */
1046 nfo = malloc (sizeof (*nfo));
1048 return; /* Uho! Expect problems! */
1049 *nfo = VLC_CANCEL_INIT;
1050 vlc_threadvar_set (&cancel_key, nfo);
1057 case VLC_SAVE_CANCEL:
1059 int *p_state = va_arg (ap, int *);
1060 *p_state = nfo->killable;
1061 nfo->killable = false;
1065 case VLC_RESTORE_CANCEL:
1067 int state = va_arg (ap, int);
1068 nfo->killable = state != 0;
1072 case VLC_TEST_CANCEL:
1073 if (nfo->killable && nfo->killed)
1075 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
1080 #if defined (LIBVLC_USE_PTHREAD)
1081 pthread_exit (PTHREAD_CANCELLED);
1082 #elif defined (WIN32)
1085 # error Not implemented!
1094 case VLC_CLEANUP_PUSH:
1096 /* cleaner is a pointer to the caller stack, no need to allocate
1097 * and copy anything. As a nice side effect, this cannot fail. */
1098 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
1099 cleaner->next = nfo->cleaners;
1100 nfo->cleaners = cleaner;
1104 case VLC_CLEANUP_POP:
1106 nfo->cleaners = nfo->cleaners->next;