]> git.sesse.net Git - vlc/blob - src/misc/threads.c
Support for cancelling self and use normal thread variable
[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
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 /**
572  * Marks a thread as cancelled. Next time the target thread reaches a
573  * cancellation point (while not having disabled cancellation), it will
574  * run its cancellation cleanup handler, the thread variable destructors, and
575  * terminate. vlc_join() must be used afterward regardless of a thread being
576  * cancelled or not.
577  */
578 void vlc_cancel (vlc_thread_t thread_id)
579 {
580 #if defined (LIBVLC_USE_PTHREAD)
581     pthread_cancel (thread_id);
582 #endif
583 }
584
585 /**
586  * Waits for a thread to complete (if needed), and destroys it.
587  * @param handle thread handle
588  * @param p_result [OUT] pointer to write the thread return value or NULL
589  * @return 0 on success, a standard error code otherwise.
590  */
591 int vlc_join (vlc_thread_t handle, void **result)
592 {
593 #if defined( LIBVLC_USE_PTHREAD )
594     return pthread_join (handle, result);
595
596 #elif defined( UNDER_CE ) || defined( WIN32 )
597     WaitForSingleObject (handle->handle, INFINITE);
598     CloseHandle (handle->handle);
599     if (result)
600         *result = handle->data;
601     free (handle);
602     return 0;
603
604 #elif defined( HAVE_KERNEL_SCHEDULER_H )
605     int32_t exit_value;
606     ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
607     if( !ret && result )
608         *result = (void *)exit_value;
609
610     return ret;
611 #endif
612 }
613
614
615 struct vlc_thread_boot
616 {
617     void * (*entry) (vlc_object_t *);
618     vlc_object_t *object;
619 };
620
621 static void *thread_entry (void *data)
622 {
623     vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
624     void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
625
626     free (data);
627 #ifndef NDEBUG
628     vlc_threadvar_set (&thread_object_key, obj);
629 #endif
630     msg_Dbg (obj, "thread started");
631     func (obj);
632     msg_Dbg (obj, "thread ended");
633
634     return NULL;
635 }
636
637 /*****************************************************************************
638  * vlc_thread_create: create a thread, inner version
639  *****************************************************************************
640  * Note that i_priority is only taken into account on platforms supporting
641  * userland real-time priority threads.
642  *****************************************************************************/
643 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
644                          const char *psz_name, void * ( *func ) ( vlc_object_t * ),
645                          int i_priority, bool b_wait )
646 {
647     int i_ret;
648     vlc_object_internals_t *p_priv = vlc_internals( p_this );
649
650     struct vlc_thread_boot *boot = malloc (sizeof (*boot));
651     if (boot == NULL)
652         return errno;
653     boot->entry = func;
654     boot->object = p_this;
655
656     vlc_object_lock( p_this );
657
658     /* Make sure we don't re-create a thread if the object has already one */
659     assert( !p_priv->b_thread );
660
661 #if defined( LIBVLC_USE_PTHREAD )
662 #ifndef __APPLE__
663     if( config_GetInt( p_this, "rt-priority" ) > 0 )
664 #endif
665     {
666         /* Hack to avoid error msg */
667         if( config_GetType( p_this, "rt-offset" ) )
668             i_priority += config_GetInt( p_this, "rt-offset" );
669     }
670 #endif
671
672     i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
673     if( i_ret == 0 )
674     {
675         if( b_wait )
676         {
677             msg_Dbg( p_this, "waiting for thread initialization" );
678             vlc_object_wait( p_this );
679         }
680
681         p_priv->b_thread = true;
682         msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
683                  (unsigned long)p_priv->thread_id, psz_name, i_priority,
684                  psz_file, i_line );
685     }
686     else
687     {
688         errno = i_ret;
689         msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
690                          psz_name, psz_file, i_line );
691     }
692
693     vlc_object_unlock( p_this );
694     return i_ret;
695 }
696
697 /*****************************************************************************
698  * vlc_thread_set_priority: set the priority of the current thread when we
699  * couldn't set it in vlc_thread_create (for instance for the main thread)
700  *****************************************************************************/
701 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
702                                int i_line, int i_priority )
703 {
704     vlc_object_internals_t *p_priv = vlc_internals( p_this );
705
706     if( !p_priv->b_thread )
707     {
708         msg_Err( p_this, "couldn't set priority of non-existent thread" );
709         return ESRCH;
710     }
711
712 #if defined( LIBVLC_USE_PTHREAD )
713 # ifndef __APPLE__
714     if( config_GetInt( p_this, "rt-priority" ) > 0 )
715 # endif
716     {
717         int i_error, i_policy;
718         struct sched_param param;
719
720         memset( &param, 0, sizeof(struct sched_param) );
721         if( config_GetType( p_this, "rt-offset" ) )
722             i_priority += config_GetInt( p_this, "rt-offset" );
723         if( i_priority <= 0 )
724         {
725             param.sched_priority = (-1) * i_priority;
726             i_policy = SCHED_OTHER;
727         }
728         else
729         {
730             param.sched_priority = i_priority;
731             i_policy = SCHED_RR;
732         }
733         if( (i_error = pthread_setschedparam( p_priv->thread_id,
734                                               i_policy, &param )) )
735         {
736             errno = i_error;
737             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
738                       psz_file, i_line );
739             i_priority = 0;
740         }
741     }
742
743 #elif defined( WIN32 ) || defined( UNDER_CE )
744     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
745
746     if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
747     {
748         msg_Warn( p_this, "couldn't set a faster priority" );
749         return 1;
750     }
751
752 #endif
753
754     return 0;
755 }
756
757 /*****************************************************************************
758  * vlc_thread_join: wait until a thread exits, inner version
759  *****************************************************************************/
760 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
761 {
762     vlc_object_internals_t *p_priv = vlc_internals( p_this );
763     int i_ret = 0;
764
765 #if defined( LIBVLC_USE_PTHREAD )
766     /* Make sure we do return if we are calling vlc_thread_join()
767      * from the joined thread */
768     if (pthread_equal (pthread_self (), p_priv->thread_id))
769     {
770         msg_Warn (p_this, "joining the active thread (VLC might crash)");
771         i_ret = pthread_detach (p_priv->thread_id);
772     }
773     else
774         i_ret = vlc_join (p_priv->thread_id, NULL);
775
776 #elif defined( UNDER_CE ) || defined( WIN32 )
777     HANDLE hThread;
778     FILETIME create_ft, exit_ft, kernel_ft, user_ft;
779     int64_t real_time, kernel_time, user_time;
780
781     if( ! DuplicateHandle(GetCurrentProcess(),
782             p_priv->thread_id->handle,
783             GetCurrentProcess(),
784             &hThread,
785             0,
786             FALSE,
787             DUPLICATE_SAME_ACCESS) )
788     {
789         p_priv->b_thread = false;
790         i_ret = GetLastError();
791         goto error;
792     }
793
794     vlc_join( p_priv->thread_id, NULL );
795
796     if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
797     {
798         real_time =
799           ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
800           ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
801         real_time /= 10;
802
803         kernel_time =
804           ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
805            kernel_ft.dwLowDateTime) / 10;
806
807         user_time =
808           ((((int64_t)user_ft.dwHighDateTime)<<32)|
809            user_ft.dwLowDateTime) / 10;
810
811         msg_Dbg( p_this, "thread times: "
812                  "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
813                  real_time/60/1000000,
814                  (double)((real_time%(60*1000000))/1000000.0),
815                  kernel_time/60/1000000,
816                  (double)((kernel_time%(60*1000000))/1000000.0),
817                  user_time/60/1000000,
818                  (double)((user_time%(60*1000000))/1000000.0) );
819     }
820     CloseHandle( hThread );
821 error:
822
823 #else
824     i_ret = vlc_join( p_priv->thread_id, NULL );
825
826 #endif
827
828     if( i_ret )
829     {
830         errno = i_ret;
831         msg_Err( p_this, "thread_join(%lu) failed at %s:%d (%m)",
832                          (unsigned long)p_priv->thread_id, psz_file, i_line );
833     }
834     else
835         msg_Dbg( p_this, "thread %lu joined (%s:%d)",
836                          (unsigned long)p_priv->thread_id, psz_file, i_line );
837
838     p_priv->b_thread = false;
839 }
840
841 void vlc_thread_cancel (vlc_object_t *obj)
842 {
843     vlc_object_internals_t *priv = vlc_internals (obj);
844
845     if (priv->b_thread)
846         vlc_cancel (priv->thread_id);
847 }
848
849 typedef struct vlc_cleanup_t
850 {
851     struct vlc_cleanup_t *next;
852     void                (*proc) (void *);
853     void                 *data;
854 } vlc_cleanup_t;
855
856 typedef struct vlc_cancel_t
857 {
858     vlc_cleanup_t *cleaners;
859     bool           killable;
860     bool           killed;
861 } vlc_cancel_t;
862
863 void vlc_control_cancel (int cmd, ...)
864 {
865 #ifdef LIBVLC_USE_PTHREAD
866     (void) cmd;
867     abort();
868 #else
869     va_list ap;
870
871     va_start (ap, cmd);
872
873     vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
874     if (nfo == NULL)
875     {
876         nfo = malloc (sizeof (*nfo));
877         if (nfo == NULL)
878             abort ();
879         nfo->cleaners = NULL;
880         nfo->killed = false;
881         nfo->killable = true;
882     }
883
884     switch (cmd)
885     {
886         case VLC_SAVE_CANCEL:
887         {
888             int *p_state = va_arg (ap, int *);
889             *p_state = nfo->killable;
890             nfo->killable = false;
891             break;
892         }
893
894         case VLC_RESTORE_CANCEL:
895         {
896             int state = va_arg (ap, int);
897             nfo->killable = state != 0;
898             break;
899         }
900
901         case VLC_TEST_CANCEL:
902             if (nfo->killable && nfo->killed)
903             {
904                 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
905                      p->proc (p->data);
906                 free (nfo);
907 #if defined (LIBVLC_USE_PTHREAD)
908                 pthread_exit (PTHREAD_CANCELLED);
909 #elif defined (WIN32)
910                 _endthread ();
911 #else
912 # error Not implemented!
913 #endif
914             }
915             break;
916
917         case VLC_DO_CANCEL:
918             nfo->killed = true;
919             break;
920     }
921     va_end (ap);
922 #endif
923 }