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