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