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