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