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