]> git.sesse.net Git - vlc/blob - src/misc/threads.c
Stub cancellation support
[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 #ifndef NDEBUG
70 /**
71  * Object running the current thread
72  */
73 static vlc_threadvar_t thread_object_key;
74
75 vlc_object_t *vlc_threadobj (void)
76 {
77     return vlc_threadvar_get (&thread_object_key);
78 }
79 #endif
80
81 vlc_threadvar_t msg_context_global_key;
82
83 #if defined(LIBVLC_USE_PTHREAD)
84 static inline unsigned long vlc_threadid (void)
85 {
86      union { pthread_t th; unsigned long int i; } v = { };
87      v.th = pthread_self ();
88      return v.i;
89 }
90
91 #if defined(HAVE_EXECINFO_H) && defined(HAVE_BACKTRACE)
92 # include <execinfo.h>
93 #endif
94
95 /*****************************************************************************
96  * vlc_thread_fatal: Report an error from the threading layer
97  *****************************************************************************
98  * This is mostly meant for debugging.
99  *****************************************************************************/
100 void vlc_pthread_fatal (const char *action, int error,
101                         const char *file, unsigned line)
102 {
103     fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
104              action, vlc_threadid (), file, line, error);
105
106     /* Sometimes strerror_r() crashes too, so make sure we print an error
107      * message before we invoke it */
108 #ifdef __GLIBC__
109     /* Avoid the strerror_r() prototype brain damage in glibc */
110     errno = error;
111     fprintf (stderr, " Error message: %m at:\n");
112 #else
113     char buf[1000];
114     const char *msg;
115
116     switch (strerror_r (error, buf, sizeof (buf)))
117     {
118         case 0:
119             msg = buf;
120             break;
121         case ERANGE: /* should never happen */
122             msg = "unknwon (too big to display)";
123             break;
124         default:
125             msg = "unknown (invalid error number)";
126             break;
127     }
128     fprintf (stderr, " Error message: %s\n", msg);
129 #endif
130     fflush (stderr);
131
132 #ifdef HAVE_BACKTRACE
133     void *stack[20];
134     int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
135     backtrace_symbols_fd (stack, len, 2);
136 #endif
137
138     abort ();
139 }
140 #else
141 void vlc_pthread_fatal (const char *action, int error,
142                         const char *file, unsigned line)
143 {
144     (void)action; (void)error; (void)file; (void)line;
145     abort();
146 }
147 #endif
148
149 /*****************************************************************************
150  * vlc_threads_init: initialize threads system
151  *****************************************************************************
152  * This function requires lazy initialization of a global lock in order to
153  * keep the library really thread-safe. Some architectures don't support this
154  * and thus do not guarantee the complete reentrancy.
155  *****************************************************************************/
156 int vlc_threads_init( void )
157 {
158     int i_ret = VLC_SUCCESS;
159
160     /* If we have lazy mutex initialization, use it. Otherwise, we just
161      * hope nothing wrong happens. */
162 #if defined( LIBVLC_USE_PTHREAD )
163     pthread_mutex_lock( &once_mutex );
164 #endif
165
166     if( i_initializations == 0 )
167     {
168         p_root = vlc_custom_create( (vlc_object_t *)NULL, sizeof( *p_root ),
169                                     VLC_OBJECT_GENERIC, "root" );
170         if( p_root == NULL )
171         {
172             i_ret = VLC_ENOMEM;
173             goto out;
174         }
175
176         /* We should be safe now. Do all the initialization stuff we want. */
177 #ifndef NDEBUG
178         vlc_threadvar_create( &thread_object_key, NULL );
179 #endif
180         vlc_threadvar_create( &msg_context_global_key, msg_StackDestroy );
181     }
182     i_initializations++;
183
184 out:
185     /* If we have lazy mutex initialization support, unlock the mutex.
186      * Otherwize, we are screwed. */
187 #if defined( LIBVLC_USE_PTHREAD )
188     pthread_mutex_unlock( &once_mutex );
189 #endif
190
191     return i_ret;
192 }
193
194 /*****************************************************************************
195  * vlc_threads_end: stop threads system
196  *****************************************************************************
197  * FIXME: This function is far from being threadsafe.
198  *****************************************************************************/
199 void vlc_threads_end( void )
200 {
201 #if defined( LIBVLC_USE_PTHREAD )
202     pthread_mutex_lock( &once_mutex );
203 #endif
204
205     assert( i_initializations > 0 );
206
207     if( i_initializations == 1 )
208     {
209         vlc_object_release( p_root );
210         vlc_threadvar_delete( &msg_context_global_key );
211 #ifndef NDEBUG
212         vlc_threadvar_delete( &thread_object_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_thread_t self = data;
447     self->data = self->entry (self->data);
448     return 0;
449 }
450 #endif
451
452 /**
453  * Creates and starts new thread.
454  *
455  * @param p_handle [OUT] pointer to write the handle of the created thread to
456  * @param entry entry point for the thread
457  * @param data data parameter given to the entry point
458  * @param priority thread priority value
459  * @return 0 on success, a standard error code on error.
460  */
461 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
462                int priority)
463 {
464     int ret;
465
466 #if defined( LIBVLC_USE_PTHREAD )
467     pthread_attr_t attr;
468     pthread_attr_init (&attr);
469
470     /* Block the signals that signals interface plugin handles.
471      * If the LibVLC caller wants to handle some signals by itself, it should
472      * block these before whenever invoking LibVLC. And it must obviously not
473      * start the VLC signals interface plugin.
474      *
475      * LibVLC will normally ignore any interruption caused by an asynchronous
476      * signal during a system call. But there may well be some buggy cases
477      * where it fails to handle EINTR (bug reports welcome). Some underlying
478      * libraries might also not handle EINTR properly.
479      */
480     sigset_t oldset;
481     {
482         sigset_t set;
483         sigemptyset (&set);
484         sigdelset (&set, SIGHUP);
485         sigaddset (&set, SIGINT);
486         sigaddset (&set, SIGQUIT);
487         sigaddset (&set, SIGTERM);
488
489         sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
490         pthread_sigmask (SIG_BLOCK, &set, &oldset);
491     }
492     {
493         struct sched_param sp = { .sched_priority = priority, };
494         int policy;
495
496         if (sp.sched_priority <= 0)
497             sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
498         else
499             sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
500
501         pthread_attr_setschedpolicy (&attr, policy);
502         pthread_attr_setschedparam (&attr, &sp);
503     }
504
505     ret = pthread_create (p_handle, &attr, entry, data);
506     pthread_sigmask (SIG_SETMASK, &oldset, NULL);
507     pthread_attr_destroy (&attr);
508
509 #elif defined( WIN32 ) || defined( UNDER_CE )
510     /* When using the MSVCRT C library you have to use the _beginthreadex
511      * function instead of CreateThread, otherwise you'll end up with
512      * memory leaks and the signal functions not working (see Microsoft
513      * Knowledge Base, article 104641) */
514     HANDLE hThread;
515     vlc_thread_t th = malloc (sizeof (*p_handle));
516
517     if (th == NULL)
518         return ENOMEM;
519
520     th->data = data;
521     th->entry = entry;
522 #if defined( UNDER_CE )
523     hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
524 #else
525     hThread = (HANDLE)(uintptr_t)
526         _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
527 #endif
528
529     if (hThread)
530     {
531         /* Thread closes the handle when exiting, duplicate it here
532          * to be on the safe side when joining. */
533         if (!DuplicateHandle (GetCurrentProcess (), hThread,
534                               GetCurrentProcess (), &th->handle, 0, FALSE,
535                               DUPLICATE_SAME_ACCESS))
536         {
537             CloseHandle (hThread);
538             free (th);
539             return ENOMEM;
540         }
541
542         ResumeThread (hThread);
543         if (priority)
544             SetThreadPriority (hThread, priority);
545
546         ret = 0;
547         *p_handle = th;
548     }
549     else
550     {
551         ret = errno;
552         free (th);
553     }
554
555 #elif defined( HAVE_KERNEL_SCHEDULER_H )
556     *p_handle = spawn_thread( entry, psz_name, priority, data );
557     ret = resume_thread( *p_handle );
558
559 #endif
560     return ret;
561 }
562
563 /**
564  * Marks a thread as cancelled. Next time the target thread reaches a
565  * cancellation point (while not having disabled cancellation), it will
566  * run its cancellation cleanup handler, the thread variable destructors, and
567  * terminate. vlc_join() must be used afterward regardless of a thread being
568  * cancelled or not.
569  */
570 void vlc_cancel (vlc_thread_t thread_id)
571 {
572 #if defined (LIBVLC_USE_PTHREAD)
573     pthread_cancel (thread_id);
574 #endif
575 }
576
577 /**
578  * Waits for a thread to complete (if needed), and destroys it.
579  * @param handle thread handle
580  * @param p_result [OUT] pointer to write the thread return value or NULL
581  * @return 0 on success, a standard error code otherwise.
582  */
583 int vlc_join (vlc_thread_t handle, void **result)
584 {
585 #if defined( LIBVLC_USE_PTHREAD )
586     return pthread_join (handle, result);
587
588 #elif defined( UNDER_CE ) || defined( WIN32 )
589     WaitForSingleObject (handle->handle, INFINITE);
590     CloseHandle (handle->handle);
591     if (result)
592         *result = handle->data;
593     free (handle);
594     return 0;
595
596 #elif defined( HAVE_KERNEL_SCHEDULER_H )
597     int32_t exit_value;
598     ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
599     if( !ret && result )
600         *result = (void *)exit_value;
601
602     return ret;
603 #endif
604 }
605
606
607 struct vlc_thread_boot
608 {
609     void * (*entry) (vlc_object_t *);
610     vlc_object_t *object;
611 };
612
613 static void *thread_entry (void *data)
614 {
615     vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
616     void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
617
618     free (data);
619 #ifndef NDEBUG
620     vlc_threadvar_set (&thread_object_key, obj);
621 #endif
622     msg_Dbg (obj, "thread started");
623     func (obj);
624     msg_Dbg (obj, "thread ended");
625
626     return NULL;
627 }
628
629 /*****************************************************************************
630  * vlc_thread_create: create a thread, inner version
631  *****************************************************************************
632  * Note that i_priority is only taken into account on platforms supporting
633  * userland real-time priority threads.
634  *****************************************************************************/
635 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
636                          const char *psz_name, void * ( *func ) ( vlc_object_t * ),
637                          int i_priority, bool b_wait )
638 {
639     int i_ret;
640     vlc_object_internals_t *p_priv = vlc_internals( p_this );
641
642     struct vlc_thread_boot *boot = malloc (sizeof (*boot));
643     if (boot == NULL)
644         return errno;
645     boot->entry = func;
646     boot->object = p_this;
647
648     vlc_object_lock( p_this );
649
650     /* Make sure we don't re-create a thread if the object has already one */
651     assert( !p_priv->b_thread );
652
653 #if defined( LIBVLC_USE_PTHREAD )
654 #ifndef __APPLE__
655     if( config_GetInt( p_this, "rt-priority" ) > 0 )
656 #endif
657     {
658         /* Hack to avoid error msg */
659         if( config_GetType( p_this, "rt-offset" ) )
660             i_priority += config_GetInt( p_this, "rt-offset" );
661     }
662 #endif
663
664     i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
665     if( i_ret == 0 )
666     {
667         if( b_wait )
668         {
669             msg_Dbg( p_this, "waiting for thread initialization" );
670             vlc_object_wait( p_this );
671         }
672
673         p_priv->b_thread = true;
674         msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
675                  (unsigned long)p_priv->thread_id, psz_name, i_priority,
676                  psz_file, i_line );
677     }
678     else
679     {
680         errno = i_ret;
681         msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
682                          psz_name, psz_file, i_line );
683     }
684
685     vlc_object_unlock( p_this );
686     return i_ret;
687 }
688
689 /*****************************************************************************
690  * vlc_thread_set_priority: set the priority of the current thread when we
691  * couldn't set it in vlc_thread_create (for instance for the main thread)
692  *****************************************************************************/
693 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
694                                int i_line, int i_priority )
695 {
696     vlc_object_internals_t *p_priv = vlc_internals( p_this );
697
698     if( !p_priv->b_thread )
699     {
700         msg_Err( p_this, "couldn't set priority of non-existent thread" );
701         return ESRCH;
702     }
703
704 #if defined( LIBVLC_USE_PTHREAD )
705 # ifndef __APPLE__
706     if( config_GetInt( p_this, "rt-priority" ) > 0 )
707 # endif
708     {
709         int i_error, i_policy;
710         struct sched_param param;
711
712         memset( &param, 0, sizeof(struct sched_param) );
713         if( config_GetType( p_this, "rt-offset" ) )
714             i_priority += config_GetInt( p_this, "rt-offset" );
715         if( i_priority <= 0 )
716         {
717             param.sched_priority = (-1) * i_priority;
718             i_policy = SCHED_OTHER;
719         }
720         else
721         {
722             param.sched_priority = i_priority;
723             i_policy = SCHED_RR;
724         }
725         if( (i_error = pthread_setschedparam( p_priv->thread_id,
726                                               i_policy, &param )) )
727         {
728             errno = i_error;
729             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
730                       psz_file, i_line );
731             i_priority = 0;
732         }
733     }
734
735 #elif defined( WIN32 ) || defined( UNDER_CE )
736     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
737
738     if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
739     {
740         msg_Warn( p_this, "couldn't set a faster priority" );
741         return 1;
742     }
743
744 #endif
745
746     return 0;
747 }
748
749 /*****************************************************************************
750  * vlc_thread_join: wait until a thread exits, inner version
751  *****************************************************************************/
752 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
753 {
754     vlc_object_internals_t *p_priv = vlc_internals( p_this );
755     int i_ret = 0;
756
757 #if defined( LIBVLC_USE_PTHREAD )
758     /* Make sure we do return if we are calling vlc_thread_join()
759      * from the joined thread */
760     if (pthread_equal (pthread_self (), p_priv->thread_id))
761     {
762         msg_Warn (p_this, "joining the active thread (VLC might crash)");
763         i_ret = pthread_detach (p_priv->thread_id);
764     }
765     else
766         i_ret = vlc_join (p_priv->thread_id, NULL);
767
768 #elif defined( UNDER_CE ) || defined( WIN32 )
769     HANDLE hThread;
770     FILETIME create_ft, exit_ft, kernel_ft, user_ft;
771     int64_t real_time, kernel_time, user_time;
772
773     if( ! DuplicateHandle(GetCurrentProcess(),
774             p_priv->thread_id->handle,
775             GetCurrentProcess(),
776             &hThread,
777             0,
778             FALSE,
779             DUPLICATE_SAME_ACCESS) )
780     {
781         p_priv->b_thread = false;
782         i_ret = GetLastError();
783         goto error;
784     }
785
786     vlc_join( p_priv->thread_id, NULL );
787
788     if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
789     {
790         real_time =
791           ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
792           ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
793         real_time /= 10;
794
795         kernel_time =
796           ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
797            kernel_ft.dwLowDateTime) / 10;
798
799         user_time =
800           ((((int64_t)user_ft.dwHighDateTime)<<32)|
801            user_ft.dwLowDateTime) / 10;
802
803         msg_Dbg( p_this, "thread times: "
804                  "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
805                  real_time/60/1000000,
806                  (double)((real_time%(60*1000000))/1000000.0),
807                  kernel_time/60/1000000,
808                  (double)((kernel_time%(60*1000000))/1000000.0),
809                  user_time/60/1000000,
810                  (double)((user_time%(60*1000000))/1000000.0) );
811     }
812     CloseHandle( hThread );
813 error:
814
815 #else
816     i_ret = vlc_join( p_priv->thread_id, NULL );
817
818 #endif
819
820     if( i_ret )
821     {
822         errno = i_ret;
823         msg_Err( p_this, "thread_join(%lu) failed at %s:%d (%m)",
824                          (unsigned long)p_priv->thread_id, psz_file, i_line );
825     }
826     else
827         msg_Dbg( p_this, "thread %lu joined (%s:%d)",
828                          (unsigned long)p_priv->thread_id, psz_file, i_line );
829
830     p_priv->b_thread = false;
831 }
832
833 void vlc_thread_cancel (vlc_object_t *obj)
834 {
835     vlc_object_internals_t *priv = vlc_internals (obj);
836
837     if (priv->b_thread)
838         vlc_cancel (priv->thread_id);
839 }
840
841 void vlc_control_cancel (int cmd, ...)
842 {
843 #ifdef LIBVLC_USE_PTHREAD
844     (void) cmd;
845     abort();
846 #else
847     static __thread struct vlc_cancel_t *stack = NULL;
848     static __thread bool killed = false, killable = true;
849     va_list ap;
850
851     va_start (ap, cmd);
852
853     switch (cmd)
854     {
855         case VLC_SAVE_CANCEL:
856         {
857             int *p_state = va_arg (ap, int *);
858             *p_state = killable;
859             killable = false;
860             break;
861         }
862
863         case VLC_RESTORE_CANCEL:
864         {
865             int state = va_arg (ap, int);
866             killable = state != 0;
867             break;
868         }
869
870         case VLC_TEST_CANCEL:
871             if (killable)
872 #ifdef WIN32
873                 _endthread ();
874 #else
875 # error Not implemented!
876 #endif
877             break;
878     }
879     va_end (ap);
880 #endif
881 }