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