]> git.sesse.net Git - vlc/blob - src/misc/threads.c
7d62c3f543ad46ce339633fbaf26c67980411297
[vlc] / src / misc / threads.c
1 /*****************************************************************************
2  * threads.c : threads implementation for the VideoLAN client
3  *****************************************************************************
4  * Copyright (C) 1999-2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          Gildas Bazin <gbazin@netcourrier.com>
10  *          Clément Sténac
11  *
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.
16  *
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.
21  *
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  *****************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32
33 #include "libvlc.h"
34 #include <stdarg.h>
35 #include <assert.h>
36 #ifdef HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39 #include <signal.h>
40
41 #define VLC_THREADS_UNINITIALIZED  0
42 #define VLC_THREADS_PENDING        1
43 #define VLC_THREADS_ERROR          2
44 #define VLC_THREADS_READY          3
45
46 /*****************************************************************************
47  * Global mutex for lazy initialization of the threads system
48  *****************************************************************************/
49 static volatile unsigned i_initializations = 0;
50
51 #if defined( LIBVLC_USE_PTHREAD )
52 # include <sched.h>
53
54 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
55 #endif
56
57 /**
58  * Global process-wide VLC object.
59  * Contains inter-instance data, such as the module cache and global mutexes.
60  */
61 static libvlc_global_data_t *p_root;
62
63 libvlc_global_data_t *vlc_global( void )
64 {
65     assert( i_initializations > 0 );
66     return p_root;
67 }
68
69 #if defined(LIBVLC_USE_PTHREAD)
70 static inline unsigned long vlc_threadid (void)
71 {
72      union { pthread_t th; unsigned long int i; } v = { };
73      v.th = pthread_self ();
74      return v.i;
75 }
76
77 #if defined(HAVE_EXECINFO_H) && defined(HAVE_BACKTRACE)
78 # include <execinfo.h>
79 #endif
80
81 /*****************************************************************************
82  * vlc_thread_fatal: Report an error from the threading layer
83  *****************************************************************************
84  * This is mostly meant for debugging.
85  *****************************************************************************/
86 void vlc_pthread_fatal (const char *action, int error,
87                         const char *file, unsigned line)
88 {
89     fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
90              action, vlc_threadid (), file, line, error);
91
92     /* Sometimes strerror_r() crashes too, so make sure we print an error
93      * message before we invoke it */
94 #ifdef __GLIBC__
95     /* Avoid the strerror_r() prototype brain damage in glibc */
96     errno = error;
97     fprintf (stderr, " Error message: %m at:\n");
98 #else
99     char buf[1000];
100     const char *msg;
101
102     switch (strerror_r (error, buf, sizeof (buf)))
103     {
104         case 0:
105             msg = buf;
106             break;
107         case ERANGE: /* should never happen */
108             msg = "unknwon (too big to display)";
109             break;
110         default:
111             msg = "unknown (invalid error number)";
112             break;
113     }
114     fprintf (stderr, " Error message: %s\n", msg);
115 #endif
116     fflush (stderr);
117
118 #ifdef HAVE_BACKTRACE
119     void *stack[20];
120     int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
121     backtrace_symbols_fd (stack, len, 2);
122 #endif
123
124     abort ();
125 }
126 #else
127 void vlc_pthread_fatal (const char *action, int error,
128                         const char *file, unsigned line)
129 {
130     (void)action; (void)error; (void)file; (void)line;
131     abort();
132 }
133
134 static vlc_threadvar_t cancel_key;
135 #endif
136
137 /**
138  * Per-thread cancellation data
139  */
140 #ifndef LIBVLC_USE_PTHREAD_CANCEL
141 typedef struct vlc_cancel_t
142 {
143     vlc_cleanup_t *cleaners;
144     bool           killable;
145     bool           killed;
146 } vlc_cancel_t;
147
148 # define VLC_CANCEL_INIT { NULL, false, true }
149 #endif
150
151 /*****************************************************************************
152  * vlc_threads_init: initialize threads system
153  *****************************************************************************
154  * This function requires lazy initialization of a global lock in order to
155  * keep the library really thread-safe. Some architectures don't support this
156  * and thus do not guarantee the complete reentrancy.
157  *****************************************************************************/
158 int vlc_threads_init( void )
159 {
160     int i_ret = VLC_SUCCESS;
161
162     /* If we have lazy mutex initialization, use it. Otherwise, we just
163      * hope nothing wrong happens. */
164 #if defined( LIBVLC_USE_PTHREAD )
165     pthread_mutex_lock( &once_mutex );
166 #endif
167
168     if( i_initializations == 0 )
169     {
170         p_root = vlc_custom_create( (vlc_object_t *)NULL, sizeof( *p_root ),
171                                     VLC_OBJECT_GENERIC, "root" );
172         if( p_root == NULL )
173         {
174             i_ret = VLC_ENOMEM;
175             goto out;
176         }
177
178         /* We should be safe now. Do all the initialization stuff we want. */
179 #ifndef LIBVLC_USE_PTHREAD_CANCEL
180         vlc_threadvar_create( &cancel_key, free );
181 #endif
182     }
183     i_initializations++;
184
185 out:
186     /* If we have lazy mutex initialization support, unlock the mutex.
187      * Otherwize, we are screwed. */
188 #if defined( LIBVLC_USE_PTHREAD )
189     pthread_mutex_unlock( &once_mutex );
190 #endif
191
192     return i_ret;
193 }
194
195 /*****************************************************************************
196  * vlc_threads_end: stop threads system
197  *****************************************************************************
198  * FIXME: This function is far from being threadsafe.
199  *****************************************************************************/
200 void vlc_threads_end( void )
201 {
202 #if defined( LIBVLC_USE_PTHREAD )
203     pthread_mutex_lock( &once_mutex );
204 #endif
205
206     assert( i_initializations > 0 );
207
208     if( i_initializations == 1 )
209     {
210         vlc_object_release( p_root );
211 #ifndef LIBVLC_USE_PTHREAD
212         vlc_threadvar_delete( &cancel_key );
213 #endif
214     }
215     i_initializations--;
216
217 #if defined( LIBVLC_USE_PTHREAD )
218     pthread_mutex_unlock( &once_mutex );
219 #endif
220 }
221
222 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
223 /* This is not prototyped under glibc, though it exists. */
224 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
225 #endif
226
227 /*****************************************************************************
228  * vlc_mutex_init: initialize a mutex
229  *****************************************************************************/
230 int vlc_mutex_init( vlc_mutex_t *p_mutex )
231 {
232 #if defined( LIBVLC_USE_PTHREAD )
233     pthread_mutexattr_t attr;
234     int                 i_result;
235
236     pthread_mutexattr_init( &attr );
237
238 # ifndef NDEBUG
239     /* Create error-checking mutex to detect problems more easily. */
240 #  if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
241     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
242 #  else
243     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
244 #  endif
245 # endif
246     i_result = pthread_mutex_init( p_mutex, &attr );
247     pthread_mutexattr_destroy( &attr );
248     return i_result;
249 #elif defined( UNDER_CE )
250     InitializeCriticalSection( &p_mutex->csection );
251     return 0;
252
253 #elif defined( WIN32 )
254     *p_mutex = CreateMutex( 0, FALSE, 0 );
255     return (*p_mutex != NULL) ? 0 : ENOMEM;
256
257 #elif defined( HAVE_KERNEL_SCHEDULER_H )
258     /* check the arguments and whether it's already been initialized */
259     if( p_mutex == NULL )
260     {
261         return B_BAD_VALUE;
262     }
263
264     if( p_mutex->init == 9999 )
265     {
266         return EALREADY;
267     }
268
269     p_mutex->lock = create_sem( 1, "BeMutex" );
270     if( p_mutex->lock < B_NO_ERROR )
271     {
272         return( -1 );
273     }
274
275     p_mutex->init = 9999;
276     return B_OK;
277
278 #endif
279 }
280
281 /*****************************************************************************
282  * vlc_mutex_init: initialize a recursive mutex (Do not use)
283  *****************************************************************************/
284 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
285 {
286 #if defined( LIBVLC_USE_PTHREAD )
287     pthread_mutexattr_t attr;
288     int                 i_result;
289
290     pthread_mutexattr_init( &attr );
291 #  if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
292     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
293 #  else
294     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
295 #  endif
296     i_result = pthread_mutex_init( p_mutex, &attr );
297     pthread_mutexattr_destroy( &attr );
298     return( i_result );
299 #elif defined( WIN32 )
300     /* Create mutex returns a recursive mutex */
301     *p_mutex = CreateMutex( 0, FALSE, 0 );
302     return (*p_mutex != NULL) ? 0 : ENOMEM;
303 #else
304 # error Unimplemented!
305 #endif
306 }
307
308
309 /*****************************************************************************
310  * vlc_mutex_destroy: destroy a mutex, inner version
311  *****************************************************************************/
312 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
313 {
314 #if defined( LIBVLC_USE_PTHREAD )
315     int val = pthread_mutex_destroy( p_mutex );
316     VLC_THREAD_ASSERT ("destroying mutex");
317
318 #elif defined( UNDER_CE )
319     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
320
321     DeleteCriticalSection( &p_mutex->csection );
322
323 #elif defined( WIN32 )
324     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
325
326     CloseHandle( *p_mutex );
327
328 #elif defined( HAVE_KERNEL_SCHEDULER_H )
329     if( p_mutex->init == 9999 )
330         delete_sem( p_mutex->lock );
331
332     p_mutex->init = 0;
333
334 #endif
335 }
336
337 /*****************************************************************************
338  * vlc_cond_init: initialize a condition
339  *****************************************************************************/
340 int __vlc_cond_init( vlc_cond_t *p_condvar )
341 {
342 #if defined( LIBVLC_USE_PTHREAD )
343     pthread_condattr_t attr;
344     int ret;
345
346     ret = pthread_condattr_init (&attr);
347     if (ret)
348         return ret;
349
350 # if !defined (_POSIX_CLOCK_SELECTION)
351    /* Fairly outdated POSIX support (that was defined in 2001) */
352 #  define _POSIX_CLOCK_SELECTION (-1)
353 # endif
354 # if (_POSIX_CLOCK_SELECTION >= 0)
355     /* NOTE: This must be the same clock as the one in mtime.c */
356     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
357 # endif
358
359     ret = pthread_cond_init (p_condvar, &attr);
360     pthread_condattr_destroy (&attr);
361     return ret;
362
363 #elif defined( UNDER_CE ) || defined( WIN32 )
364     /* Create an auto-reset event. */
365     *p_condvar = CreateEvent( NULL,   /* no security */
366                               FALSE,  /* auto-reset event */
367                               FALSE,  /* start non-signaled */
368                               NULL ); /* unnamed */
369     return *p_condvar ? 0 : ENOMEM;
370
371 #elif defined( HAVE_KERNEL_SCHEDULER_H )
372     if( !p_condvar )
373     {
374         return B_BAD_VALUE;
375     }
376
377     if( p_condvar->init == 9999 )
378     {
379         return EALREADY;
380     }
381
382     p_condvar->thread = -1;
383     p_condvar->init = 9999;
384     return 0;
385
386 #endif
387 }
388
389 /*****************************************************************************
390  * vlc_cond_destroy: destroy a condition, inner version
391  *****************************************************************************/
392 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
393 {
394 #if defined( LIBVLC_USE_PTHREAD )
395     int val = pthread_cond_destroy( p_condvar );
396     VLC_THREAD_ASSERT ("destroying condition");
397
398 #elif defined( UNDER_CE ) || defined( WIN32 )
399     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
400
401     CloseHandle( *p_condvar );
402
403 #elif defined( HAVE_KERNEL_SCHEDULER_H )
404     p_condvar->init = 0;
405
406 #endif
407 }
408
409 /*****************************************************************************
410  * vlc_tls_create: create a thread-local variable
411  *****************************************************************************/
412 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
413 {
414     int i_ret;
415
416 #if defined( LIBVLC_USE_PTHREAD )
417     i_ret =  pthread_key_create( p_tls, destr );
418 #elif defined( UNDER_CE )
419     i_ret = ENOSYS;
420 #elif defined( WIN32 )
421     /* FIXME: remember/use the destr() callback and stop leaking whatever */
422     *p_tls = TlsAlloc();
423     i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
424 #else
425 # error Unimplemented!
426 #endif
427     return i_ret;
428 }
429
430 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
431 {
432 #if defined( LIBVLC_USE_PTHREAD )
433     pthread_key_delete (*p_tls);
434 #elif defined( UNDER_CE )
435 #elif defined( WIN32 )
436     TlsFree (*p_tls);
437 #else
438 # error Unimplemented!
439 #endif
440 }
441
442 #if defined (LIBVLC_USE_PTHREAD)
443 #elif defined (WIN32)
444 static unsigned __stdcall vlc_entry (void *data)
445 {
446     vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
447     vlc_thread_t self = data;
448
449     vlc_threadvar_set (&cancel_key, &cancel_data);
450     self->data = self->entry (self->data);
451     return 0;
452 }
453 #endif
454
455 /**
456  * Creates and starts new thread.
457  *
458  * @param p_handle [OUT] pointer to write the handle of the created thread to
459  * @param entry entry point for the thread
460  * @param data data parameter given to the entry point
461  * @param priority thread priority value
462  * @return 0 on success, a standard error code on error.
463  */
464 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
465                int priority)
466 {
467     int ret;
468
469 #if defined( LIBVLC_USE_PTHREAD )
470     pthread_attr_t attr;
471     pthread_attr_init (&attr);
472
473     /* Block the signals that signals interface plugin handles.
474      * If the LibVLC caller wants to handle some signals by itself, it should
475      * block these before whenever invoking LibVLC. And it must obviously not
476      * start the VLC signals interface plugin.
477      *
478      * LibVLC will normally ignore any interruption caused by an asynchronous
479      * signal during a system call. But there may well be some buggy cases
480      * where it fails to handle EINTR (bug reports welcome). Some underlying
481      * libraries might also not handle EINTR properly.
482      */
483     sigset_t oldset;
484     {
485         sigset_t set;
486         sigemptyset (&set);
487         sigdelset (&set, SIGHUP);
488         sigaddset (&set, SIGINT);
489         sigaddset (&set, SIGQUIT);
490         sigaddset (&set, SIGTERM);
491
492         sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
493         pthread_sigmask (SIG_BLOCK, &set, &oldset);
494     }
495     {
496         struct sched_param sp = { .sched_priority = priority, };
497         int policy;
498
499         if (sp.sched_priority <= 0)
500             sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
501         else
502             sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
503
504         pthread_attr_setschedpolicy (&attr, policy);
505         pthread_attr_setschedparam (&attr, &sp);
506     }
507
508     ret = pthread_create (p_handle, &attr, entry, data);
509     pthread_sigmask (SIG_SETMASK, &oldset, NULL);
510     pthread_attr_destroy (&attr);
511
512 #elif defined( WIN32 ) || defined( UNDER_CE )
513     /* When using the MSVCRT C library you have to use the _beginthreadex
514      * function instead of CreateThread, otherwise you'll end up with
515      * memory leaks and the signal functions not working (see Microsoft
516      * Knowledge Base, article 104641) */
517     HANDLE hThread;
518     vlc_thread_t th = malloc (sizeof (*th));
519
520     if (th == NULL)
521         return ENOMEM;
522
523     th->data = data;
524     th->entry = entry;
525 #if defined( UNDER_CE )
526     hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
527 #else
528     hThread = (HANDLE)(uintptr_t)
529         _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
530 #endif
531
532     if (hThread)
533     {
534         /* Thread closes the handle when exiting, duplicate it here
535          * to be on the safe side when joining. */
536         if (!DuplicateHandle (GetCurrentProcess (), hThread,
537                               GetCurrentProcess (), &th->handle, 0, FALSE,
538                               DUPLICATE_SAME_ACCESS))
539         {
540             CloseHandle (hThread);
541             free (th);
542             return ENOMEM;
543         }
544
545         ResumeThread (hThread);
546         if (priority)
547             SetThreadPriority (hThread, priority);
548
549         ret = 0;
550         *p_handle = th;
551     }
552     else
553     {
554         ret = errno;
555         free (th);
556     }
557
558 #elif defined( HAVE_KERNEL_SCHEDULER_H )
559     *p_handle = spawn_thread( entry, psz_name, priority, data );
560     ret = resume_thread( *p_handle );
561
562 #endif
563     return ret;
564 }
565
566 #if defined (WIN32)
567 /* APC procedure for thread cancellation */
568 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
569 {
570     (void)dummy;
571     vlc_control_cancel (VLC_DO_CANCEL);
572 }
573 #endif
574
575 /**
576  * Marks a thread as cancelled. Next time the target thread reaches a
577  * cancellation point (while not having disabled cancellation), it will
578  * run its cancellation cleanup handler, the thread variable destructors, and
579  * terminate. vlc_join() must be used afterward regardless of a thread being
580  * cancelled or not.
581  */
582 void vlc_cancel (vlc_thread_t thread_id)
583 {
584 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
585     pthread_cancel (thread_id);
586 #elif defined (WIN32)
587     QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
588 #else
589 #   warning vlc_cancel is not implemented!
590 #endif
591 }
592
593 /**
594  * Waits for a thread to complete (if needed), and destroys it.
595  * This is a cancellation point; in case of cancellation, the join does _not_
596  * occur.
597  *
598  * @param handle thread handle
599  * @param p_result [OUT] pointer to write the thread return value or NULL
600  * @return 0 on success, a standard error code otherwise.
601  */
602 void vlc_join (vlc_thread_t handle, void **result)
603 {
604 #if defined( LIBVLC_USE_PTHREAD )
605     int val = pthread_join (handle, result);
606     if (val)
607         vlc_pthread_fatal ("joining thread", val, __FILE__, __LINE__);
608
609 #elif defined( UNDER_CE ) || defined( WIN32 )
610     do
611         vlc_testcancel ();
612     while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
613                                                         == WAIT_IO_COMPLETION);
614
615     CloseHandle (handle->handle);
616     if (result)
617         *result = handle->data;
618     free (handle);
619
620 #elif defined( HAVE_KERNEL_SCHEDULER_H )
621     int32_t exit_value;
622     int val = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
623     if( !val && result )
624         *result = (void *)exit_value;
625
626 #endif
627 }
628
629
630 struct vlc_thread_boot
631 {
632     void * (*entry) (vlc_object_t *);
633     vlc_object_t *object;
634 };
635
636 static void *thread_entry (void *data)
637 {
638     vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
639     void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
640
641     free (data);
642     msg_Dbg (obj, "thread started");
643     func (obj);
644     msg_Dbg (obj, "thread ended");
645
646     return NULL;
647 }
648
649 /*****************************************************************************
650  * vlc_thread_create: create a thread, inner version
651  *****************************************************************************
652  * Note that i_priority is only taken into account on platforms supporting
653  * userland real-time priority threads.
654  *****************************************************************************/
655 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
656                          const char *psz_name, void * ( *func ) ( vlc_object_t * ),
657                          int i_priority, bool b_wait )
658 {
659     int i_ret;
660     vlc_object_internals_t *p_priv = vlc_internals( p_this );
661
662     struct vlc_thread_boot *boot = malloc (sizeof (*boot));
663     if (boot == NULL)
664         return errno;
665     boot->entry = func;
666     boot->object = p_this;
667
668     vlc_object_lock( p_this );
669
670     /* Make sure we don't re-create a thread if the object has already one */
671     assert( !p_priv->b_thread );
672
673 #if defined( LIBVLC_USE_PTHREAD )
674 #ifndef __APPLE__
675     if( config_GetInt( p_this, "rt-priority" ) > 0 )
676 #endif
677     {
678         /* Hack to avoid error msg */
679         if( config_GetType( p_this, "rt-offset" ) )
680             i_priority += config_GetInt( p_this, "rt-offset" );
681     }
682 #endif
683
684     i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
685     if( i_ret == 0 )
686     {
687         if( b_wait )
688         {
689             msg_Dbg( p_this, "waiting for thread initialization" );
690             vlc_object_wait( p_this );
691         }
692
693         p_priv->b_thread = true;
694         msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
695                  (unsigned long)p_priv->thread_id, psz_name, i_priority,
696                  psz_file, i_line );
697     }
698     else
699     {
700         errno = i_ret;
701         msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
702                          psz_name, psz_file, i_line );
703     }
704
705     vlc_object_unlock( p_this );
706     return i_ret;
707 }
708
709 /*****************************************************************************
710  * vlc_thread_set_priority: set the priority of the current thread when we
711  * couldn't set it in vlc_thread_create (for instance for the main thread)
712  *****************************************************************************/
713 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
714                                int i_line, int i_priority )
715 {
716     vlc_object_internals_t *p_priv = vlc_internals( p_this );
717
718     if( !p_priv->b_thread )
719     {
720         msg_Err( p_this, "couldn't set priority of non-existent thread" );
721         return ESRCH;
722     }
723
724 #if defined( LIBVLC_USE_PTHREAD )
725 # ifndef __APPLE__
726     if( config_GetInt( p_this, "rt-priority" ) > 0 )
727 # endif
728     {
729         int i_error, i_policy;
730         struct sched_param param;
731
732         memset( &param, 0, sizeof(struct sched_param) );
733         if( config_GetType( p_this, "rt-offset" ) )
734             i_priority += config_GetInt( p_this, "rt-offset" );
735         if( i_priority <= 0 )
736         {
737             param.sched_priority = (-1) * i_priority;
738             i_policy = SCHED_OTHER;
739         }
740         else
741         {
742             param.sched_priority = i_priority;
743             i_policy = SCHED_RR;
744         }
745         if( (i_error = pthread_setschedparam( p_priv->thread_id,
746                                               i_policy, &param )) )
747         {
748             errno = i_error;
749             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
750                       psz_file, i_line );
751             i_priority = 0;
752         }
753     }
754
755 #elif defined( WIN32 ) || defined( UNDER_CE )
756     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
757
758     if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
759     {
760         msg_Warn( p_this, "couldn't set a faster priority" );
761         return 1;
762     }
763
764 #endif
765
766     return 0;
767 }
768
769 /*****************************************************************************
770  * vlc_thread_join: wait until a thread exits, inner version
771  *****************************************************************************/
772 void __vlc_thread_join( vlc_object_t *p_this )
773 {
774     vlc_object_internals_t *p_priv = vlc_internals( p_this );
775
776 #if defined( LIBVLC_USE_PTHREAD )
777     vlc_join (p_priv->thread_id, NULL);
778
779 #elif defined( UNDER_CE ) || defined( WIN32 )
780     HANDLE hThread;
781     FILETIME create_ft, exit_ft, kernel_ft, user_ft;
782     int64_t real_time, kernel_time, user_time;
783
784     if( ! DuplicateHandle(GetCurrentProcess(),
785             p_priv->thread_id->handle,
786             GetCurrentProcess(),
787             &hThread,
788             0,
789             FALSE,
790             DUPLICATE_SAME_ACCESS) )
791     {
792         p_priv->b_thread = false;
793         return; /* We have a problem! */
794     }
795
796     vlc_join( p_priv->thread_id, NULL );
797
798     if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
799     {
800         real_time =
801           ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
802           ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
803         real_time /= 10;
804
805         kernel_time =
806           ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
807            kernel_ft.dwLowDateTime) / 10;
808
809         user_time =
810           ((((int64_t)user_ft.dwHighDateTime)<<32)|
811            user_ft.dwLowDateTime) / 10;
812
813         msg_Dbg( p_this, "thread times: "
814                  "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
815                  real_time/60/1000000,
816                  (double)((real_time%(60*1000000))/1000000.0),
817                  kernel_time/60/1000000,
818                  (double)((kernel_time%(60*1000000))/1000000.0),
819                  user_time/60/1000000,
820                  (double)((user_time%(60*1000000))/1000000.0) );
821     }
822     CloseHandle( hThread );
823
824 #else
825     vlc_join( p_priv->thread_id, NULL );
826
827 #endif
828
829     p_priv->b_thread = false;
830 }
831
832 void vlc_thread_cancel (vlc_object_t *obj)
833 {
834     vlc_object_internals_t *priv = vlc_internals (obj);
835
836     if (priv->b_thread)
837         vlc_cancel (priv->thread_id);
838 }
839
840 void vlc_control_cancel (int cmd, ...)
841 {
842     /* NOTE: This function only modifies thread-specific data, so there is no
843      * need to lock anything. */
844 #ifdef LIBVLC_USE_PTHREAD_CANCEL
845     (void) cmd;
846     assert (0);
847 #else
848     va_list ap;
849
850     va_start (ap, cmd);
851
852     vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
853     if (nfo == NULL)
854     {
855 #ifdef WIN32
856         /* Main thread - cannot be cancelled anyway */
857         return;
858 #else
859         nfo = malloc (sizeof (*nfo));
860         if (nfo == NULL)
861             return; /* Uho! Expect problems! */
862         *nfo = VLC_CANCEL_INIT;
863         vlc_threadvar_set (&cancel_key, nfo);
864 #endif
865     }
866
867     switch (cmd)
868     {
869         case VLC_SAVE_CANCEL:
870         {
871             int *p_state = va_arg (ap, int *);
872             *p_state = nfo->killable;
873             nfo->killable = false;
874             break;
875         }
876
877         case VLC_RESTORE_CANCEL:
878         {
879             int state = va_arg (ap, int);
880             nfo->killable = state != 0;
881             break;
882         }
883
884         case VLC_TEST_CANCEL:
885             if (nfo->killable && nfo->killed)
886             {
887                 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
888                      p->proc (p->data);
889                 free (nfo);
890 #if defined (LIBVLC_USE_PTHREAD)
891                 pthread_exit (PTHREAD_CANCELLED);
892 #elif defined (WIN32)
893                 _endthread ();
894 #else
895 # error Not implemented!
896 #endif
897             }
898             break;
899
900         case VLC_DO_CANCEL:
901             nfo->killed = true;
902             break;
903
904         case VLC_CLEANUP_PUSH:
905         {
906             /* cleaner is a pointer to the caller stack, no need to allocate
907              * and copy anything. As a nice side effect, this cannot fail. */
908             vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
909             cleaner->next = nfo->cleaners;
910             nfo->cleaners = cleaner;
911             break;
912         }
913
914         case VLC_CLEANUP_POP:
915         {
916             nfo->cleaners = nfo->cleaners->next;
917             break;
918         }
919     }
920     va_end (ap);
921 #endif
922 }