]> git.sesse.net Git - vlc/blob - src/misc/threads.c
Use %m on GLIBC to work-around strerror_r prototype problems
[vlc] / src / misc / threads.c
1 /*****************************************************************************
2  * threads.c : threads implementation for the VideoLAN client
3  *****************************************************************************
4  * Copyright (C) 1999-2007 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/vlc.h>
32
33 #include "libvlc.h"
34 #include <assert.h>
35 #ifdef HAVE_UNISTD_H
36 # include <unistd.h>
37 #endif
38
39 #define VLC_THREADS_UNINITIALIZED  0
40 #define VLC_THREADS_PENDING        1
41 #define VLC_THREADS_ERROR          2
42 #define VLC_THREADS_READY          3
43
44 /*****************************************************************************
45  * Global mutex for lazy initialization of the threads system
46  *****************************************************************************/
47 static volatile unsigned i_initializations = 0;
48 static volatile int i_status = VLC_THREADS_UNINITIALIZED;
49 static vlc_object_t *p_root;
50
51 #if defined( UNDER_CE )
52 #elif defined( WIN32 )
53
54 /* following is only available on NT/2000/XP and above */
55 static SIGNALOBJECTANDWAIT pf_SignalObjectAndWait = NULL;
56
57 /*
58 ** On Windows NT/2K/XP we use a slow mutex implementation but which
59 ** allows us to correctly implement condition variables.
60 ** You can also use the faster Win9x implementation but you might
61 ** experience problems with it.
62 */
63 static vlc_bool_t          b_fast_mutex = VLC_FALSE;
64 /*
65 ** On Windows 9x/Me you can use a fast but incorrect condition variables
66 ** implementation (more precisely there is a possibility for a race
67 ** condition to happen).
68 ** However it is possible to use slower alternatives which are more robust.
69 ** Currently you can choose between implementation 0 (which is the
70 ** fastest but slightly incorrect), 1 (default) and 2.
71 */
72 static int i_win9x_cv = 1;
73
74 #elif defined( HAVE_KERNEL_SCHEDULER_H )
75 #elif defined( LIBVLC_USE_PTHREAD )
76 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
77 #endif
78
79 vlc_threadvar_t msg_context_global_key;
80
81 #if defined(LIBVLC_USE_PTHREAD)
82 static inline unsigned long vlc_threadid (void)
83 {
84      union { pthread_t th; unsigned long int i; } v = { };
85      v.th = pthread_self ();
86      return v.i;
87 }
88
89
90 /*****************************************************************************
91  * vlc_thread_fatal: Report an error from the threading layer
92  *****************************************************************************
93  * This is mostly meant for debugging.
94  *****************************************************************************/
95 void vlc_pthread_fatal (const char *action, int error,
96                         const char *file, unsigned line)
97 {
98     fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
99              action, vlc_threadid (), file, line, error);
100     fflush (stderr);
101
102     /* Sometimes strerror_r() crashes too, so make sure we print an error
103      * message before we invoke it */
104 #ifdef __GLIBC__
105     /* Avoid the strerror_r() prototype brain damage in glibc */
106     errno = error;
107     fprintf (stderr, " Error message: %m\n");
108 #else
109     char buf[1000];
110     const char *msg;
111
112     switch (sterror_r (error, buf, sizeof (buf)))
113     {
114         case 0:
115             msg = buf;
116             break;
117         case ERANGE: /* should never happen */
118             msg = "unknwon (too big to display)";
119             break;
120         default:
121             msg = "unknown (invalid error number)";
122             break;
123     }
124     fprintf (stderr, " Error message: %s\n", msg);
125 #endif
126
127     fflush (stderr);
128     abort ();
129 }
130 #endif
131
132
133 /*****************************************************************************
134  * vlc_threads_init: initialize threads system
135  *****************************************************************************
136  * This function requires lazy initialization of a global lock in order to
137  * keep the library really thread-safe. Some architectures don't support this
138  * and thus do not guarantee the complete reentrancy.
139  *****************************************************************************/
140 int __vlc_threads_init( vlc_object_t *p_this )
141 {
142     libvlc_global_data_t *p_libvlc_global = (libvlc_global_data_t *)p_this;
143     int i_ret = VLC_SUCCESS;
144
145     /* If we have lazy mutex initialization, use it. Otherwise, we just
146      * hope nothing wrong happens. */
147 #if defined( UNDER_CE )
148 #elif defined( WIN32 )
149     if( IsDebuggerPresent() )
150     {
151         /* SignalObjectAndWait() is problematic under a debugger */
152         b_fast_mutex = VLC_TRUE;
153         i_win9x_cv = 1;
154     }
155 #elif defined( HAVE_KERNEL_SCHEDULER_H )
156 #elif defined( LIBVLC_USE_PTHREAD )
157     pthread_mutex_lock( &once_mutex );
158 #endif
159
160     if( i_status == VLC_THREADS_UNINITIALIZED )
161     {
162         i_status = VLC_THREADS_PENDING;
163
164         /* We should be safe now. Do all the initialization stuff we want. */
165         p_libvlc_global->b_ready = VLC_FALSE;
166
167 #if defined( UNDER_CE )
168         /* Nothing to initialize */
169
170 #elif defined( WIN32 )
171         /* Dynamically get the address of SignalObjectAndWait */
172         if( GetVersion() < 0x80000000 )
173         {
174             HINSTANCE hInstLib;
175
176             /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
177             hInstLib = LoadLibrary( "kernel32" );
178             if( hInstLib )
179             {
180                 pf_SignalObjectAndWait =
181                     (SIGNALOBJECTANDWAIT)GetProcAddress( hInstLib,
182                                                      "SignalObjectAndWait" );
183             }
184         }
185
186 #elif defined( HAVE_KERNEL_SCHEDULER_H )
187 #elif defined( LIBVLC_USE_PTHREAD )
188 #endif
189
190         p_root = vlc_object_create( p_libvlc_global, VLC_OBJECT_GLOBAL );
191         if( p_root == NULL )
192             i_ret = VLC_ENOMEM;
193
194         if( i_ret )
195         {
196             i_status = VLC_THREADS_ERROR;
197         }
198         else
199         {
200             i_initializations++;
201             i_status = VLC_THREADS_READY;
202         }
203
204         vlc_threadvar_create( p_root, &msg_context_global_key );
205     }
206     else
207     {
208         /* Just increment the initialization count */
209         i_initializations++;
210     }
211
212     /* If we have lazy mutex initialization support, unlock the mutex;
213      * otherwize, do a naive wait loop. */
214 #if defined( UNDER_CE )
215     while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
216 #elif defined( WIN32 )
217     while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
218 #elif defined( HAVE_KERNEL_SCHEDULER_H )
219     while( i_status == VLC_THREADS_PENDING ) msleep( THREAD_SLEEP );
220 #elif defined( LIBVLC_USE_PTHREAD )
221     pthread_mutex_unlock( &once_mutex );
222 #endif
223
224     if( i_status != VLC_THREADS_READY )
225     {
226         return VLC_ETHREAD;
227     }
228
229     return i_ret;
230 }
231
232 /*****************************************************************************
233  * vlc_threads_end: stop threads system
234  *****************************************************************************
235  * FIXME: This function is far from being threadsafe.
236  *****************************************************************************/
237 int __vlc_threads_end( vlc_object_t *p_this )
238 {
239     (void)p_this;
240 #if defined( UNDER_CE )
241 #elif defined( WIN32 )
242 #elif defined( HAVE_KERNEL_SCHEDULER_H )
243 #elif defined( LIBVLC_USE_PTHREAD )
244     pthread_mutex_lock( &once_mutex );
245 #endif
246
247     if( i_initializations == 0 )
248         return VLC_EGENERIC;
249
250     i_initializations--;
251     if( i_initializations == 0 )
252     {
253         i_status = VLC_THREADS_UNINITIALIZED;
254         vlc_object_destroy( p_root );
255     }
256
257 #if defined( UNDER_CE )
258 #elif defined( WIN32 )
259 #elif defined( HAVE_KERNEL_SCHEDULER_H )
260 #elif defined( LIBVLC_USE_PTHREAD )
261     pthread_mutex_unlock( &once_mutex );
262 #endif
263     return VLC_SUCCESS;
264 }
265
266 #ifdef __linux__
267 /* This is not prototyped under Linux, though it exists. */
268 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
269 #endif
270
271 /*****************************************************************************
272  * vlc_mutex_init: initialize a mutex
273  *****************************************************************************/
274 int __vlc_mutex_init( vlc_mutex_t *p_mutex )
275 {
276 #if defined( UNDER_CE )
277     InitializeCriticalSection( &p_mutex->csection );
278     return 0;
279
280 #elif defined( WIN32 )
281     /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
282      * function and have a 100% correct vlc_cond_wait() implementation.
283      * As this function is not available on Win9x, we can use the faster
284      * CriticalSections */
285     if( pf_SignalObjectAndWait && !b_fast_mutex )
286     {
287         /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
288         p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
289         return ( p_mutex->mutex != NULL ? 0 : 1 );
290     }
291     else
292     {
293         p_mutex->mutex = NULL;
294         InitializeCriticalSection( &p_mutex->csection );
295         return 0;
296     }
297
298 #elif defined( HAVE_KERNEL_SCHEDULER_H )
299     /* check the arguments and whether it's already been initialized */
300     if( p_mutex == NULL )
301     {
302         return B_BAD_VALUE;
303     }
304
305     if( p_mutex->init == 9999 )
306     {
307         return EALREADY;
308     }
309
310     p_mutex->lock = create_sem( 1, "BeMutex" );
311     if( p_mutex->lock < B_NO_ERROR )
312     {
313         return( -1 );
314     }
315
316     p_mutex->init = 9999;
317     return B_OK;
318
319 #elif defined( LIBVLC_USE_PTHREAD )
320 # ifndef NDEBUG
321     {
322         /* Create error-checking mutex to detect problems more easily. */
323         pthread_mutexattr_t attr;
324         int                 i_result;
325
326         pthread_mutexattr_init( &attr );
327 #   if defined(SYS_LINUX)
328         pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
329 #   else
330         pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
331 #   endif
332
333         i_result = pthread_mutex_init( &p_mutex->mutex, &attr );
334         pthread_mutexattr_destroy( &attr );
335         return( i_result );
336     }
337 # endif /* NDEBUG */
338     return pthread_mutex_init( &p_mutex->mutex, NULL );
339
340 #endif
341 }
342
343 /*****************************************************************************
344  * vlc_mutex_init: initialize a recursive mutex (Do not use)
345  *****************************************************************************/
346 int __vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
347 {
348 #if defined( WIN32 )
349     /* Create mutex returns a recursive mutex */
350     p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
351     return ( p_mutex->mutex != NULL ? 0 : 1 );
352 #elif defined( LIBVLC_USE_PTHREAD )
353     pthread_mutexattr_t attr;
354     int                 i_result;
355
356     pthread_mutexattr_init( &attr );
357 # ifndef NDEBUG
358     /* Create error-checking mutex to detect problems more easily. */
359 #   if defined(SYS_LINUX)
360     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
361 #   else
362     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
363 #   endif
364 # endif
365     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
366     i_result = pthread_mutex_init( &p_mutex->mutex, &attr );
367     pthread_mutexattr_destroy( &attr );
368     return( i_result );
369 #else
370 # error Unimplemented!
371 #endif
372 }
373
374
375 /*****************************************************************************
376  * vlc_mutex_destroy: destroy a mutex, inner version
377  *****************************************************************************/
378 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
379 {
380 #if defined( UNDER_CE )
381     DeleteCriticalSection( &p_mutex->csection );
382
383 #elif defined( WIN32 )
384     if( p_mutex->mutex )
385         CloseHandle( p_mutex->mutex );
386     else
387         DeleteCriticalSection( &p_mutex->csection );
388
389 #elif defined( HAVE_KERNEL_SCHEDULER_H )
390     if( p_mutex->init == 9999 )
391         delete_sem( p_mutex->lock );
392
393     p_mutex->init = 0;
394
395 #elif defined( LIBVLC_USE_PTHREAD )
396     int val = pthread_mutex_destroy( &p_mutex->mutex );
397     VLC_THREAD_ASSERT ("destroying mutex");
398
399 #endif
400 }
401
402 /*****************************************************************************
403  * vlc_cond_init: initialize a condition
404  *****************************************************************************/
405 int __vlc_cond_init( vlc_cond_t *p_condvar )
406 {
407 #if defined( UNDER_CE )
408     /* Initialize counter */
409     p_condvar->i_waiting_threads = 0;
410
411     /* Create an auto-reset event. */
412     p_condvar->event = CreateEvent( NULL,   /* no security */
413                                     FALSE,  /* auto-reset event */
414                                     FALSE,  /* start non-signaled */
415                                     NULL ); /* unnamed */
416     return !p_condvar->event;
417
418 #elif defined( WIN32 )
419     /* Initialize counter */
420     p_condvar->i_waiting_threads = 0;
421
422     /* Misc init */
423     p_condvar->i_win9x_cv = i_win9x_cv;
424     p_condvar->SignalObjectAndWait = pf_SignalObjectAndWait;
425
426     if( (p_condvar->SignalObjectAndWait && !b_fast_mutex)
427         || p_condvar->i_win9x_cv == 0 )
428     {
429         /* Create an auto-reset event. */
430         p_condvar->event = CreateEvent( NULL,   /* no security */
431                                         FALSE,  /* auto-reset event */
432                                         FALSE,  /* start non-signaled */
433                                         NULL ); /* unnamed */
434
435         p_condvar->semaphore = NULL;
436         return !p_condvar->event;
437     }
438     else
439     {
440         p_condvar->semaphore = CreateSemaphore( NULL,       /* no security */
441                                                 0,          /* initial count */
442                                                 0x7fffffff, /* max count */
443                                                 NULL );     /* unnamed */
444
445         if( p_condvar->i_win9x_cv == 1 )
446             /* Create a manual-reset event initially signaled. */
447             p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
448         else
449             /* Create a auto-reset event. */
450             p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
451
452         InitializeCriticalSection( &p_condvar->csection );
453
454         return !p_condvar->semaphore || !p_condvar->event;
455     }
456
457 #elif defined( HAVE_KERNEL_SCHEDULER_H )
458     if( !p_condvar )
459     {
460         return B_BAD_VALUE;
461     }
462
463     if( p_condvar->init == 9999 )
464     {
465         return EALREADY;
466     }
467
468     p_condvar->thread = -1;
469     p_condvar->init = 9999;
470     return 0;
471
472 #elif defined( LIBVLC_USE_PTHREAD )
473     pthread_condattr_t attr;
474     int ret;
475
476     ret = pthread_condattr_init (&attr);
477     if (ret)
478         return ret;
479
480 # if !defined (_POSIX_CLOCK_SELECTION)
481    /* Fairly outdated POSIX support (that was defined in 2001) */
482 #  define _POSIX_CLOCK_SELECTION (-1)
483 # endif
484 # if (_POSIX_CLOCK_SELECTION >= 0)
485     /* NOTE: This must be the same clock as the one in mtime.c */
486     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
487 # endif
488
489     ret = pthread_cond_init (&p_condvar->cond, &attr);
490     pthread_condattr_destroy (&attr);
491     return ret;
492
493 #endif
494 }
495
496 /*****************************************************************************
497  * vlc_cond_destroy: destroy a condition, inner version
498  *****************************************************************************/
499 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
500 {
501 #if defined( UNDER_CE )
502     CloseHandle( p_condvar->event );
503
504 #elif defined( WIN32 )
505     if( !p_condvar->semaphore )
506         CloseHandle( p_condvar->event );
507     else
508     {
509         CloseHandle( p_condvar->event );
510         CloseHandle( p_condvar->semaphore );
511     }
512
513     if( p_condvar->semaphore != NULL )
514         DeleteCriticalSection( &p_condvar->csection );
515
516 #elif defined( HAVE_KERNEL_SCHEDULER_H )
517     p_condvar->init = 0;
518
519 #elif defined( LIBVLC_USE_PTHREAD )
520     int val = pthread_cond_destroy( &p_condvar->cond );
521     VLC_THREAD_ASSERT ("destroying condition");
522
523 #endif
524 }
525
526 /*****************************************************************************
527  * vlc_tls_create: create a thread-local variable
528  *****************************************************************************/
529 int __vlc_threadvar_create( vlc_threadvar_t *p_tls )
530 {
531     int i_ret = -1;
532
533 #if defined( HAVE_KERNEL_SCHEDULER_H )
534 # error Unimplemented!
535 #elif defined( UNDER_CE ) || defined( WIN32 )
536 #elif defined( WIN32 )
537     p_tls->handle = TlsAlloc();
538     i_ret = !( p_tls->handle == 0xFFFFFFFF );
539
540 #elif defined( LIBVLC_USE_PTHREAD )
541     i_ret =  pthread_key_create( &p_tls->handle, NULL );
542 #endif
543     return i_ret;
544 }
545
546 /*****************************************************************************
547  * vlc_thread_create: create a thread, inner version
548  *****************************************************************************
549  * Note that i_priority is only taken into account on platforms supporting
550  * userland real-time priority threads.
551  *****************************************************************************/
552 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
553                          const char *psz_name, void * ( *func ) ( void * ),
554                          int i_priority, vlc_bool_t b_wait )
555 {
556     int i_ret;
557     void *p_data = (void *)p_this;
558     vlc_object_internals_t *p_priv = p_this->p_internals;
559
560     vlc_mutex_lock( &p_this->object_lock );
561
562 #if defined( WIN32 ) || defined( UNDER_CE )
563     {
564         /* When using the MSVCRT C library you have to use the _beginthreadex
565          * function instead of CreateThread, otherwise you'll end up with
566          * memory leaks and the signal functions not working (see Microsoft
567          * Knowledge Base, article 104641) */
568 #if defined( UNDER_CE )
569         DWORD  threadId;
570         HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
571                                       (LPVOID)p_data, CREATE_SUSPENDED,
572                       &threadId );
573 #else
574         unsigned threadId;
575         uintptr_t hThread = _beginthreadex( NULL, 0,
576                         (LPTHREAD_START_ROUTINE)func,
577                                             (void*)p_data, CREATE_SUSPENDED,
578                         &threadId );
579 #endif
580         p_priv->thread_id.id = (DWORD)threadId;
581         p_priv->thread_id.hThread = (HANDLE)hThread;
582         ResumeThread((HANDLE)hThread);
583     }
584
585     i_ret = ( p_priv->thread_id.hThread ? 0 : 1 );
586
587     if( !i_ret && i_priority )
588     {
589         if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
590         {
591             msg_Warn( p_this, "couldn't set a faster priority" );
592             i_priority = 0;
593         }
594     }
595
596 #elif defined( HAVE_KERNEL_SCHEDULER_H )
597     p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
598                                       i_priority, p_data );
599     i_ret = resume_thread( p_priv->thread_id );
600
601 #elif defined( LIBVLC_USE_PTHREAD )
602     i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
603
604 #ifndef __APPLE__
605     if( config_GetInt( p_this, "rt-priority" ) )
606 #endif
607     {
608         int i_error, i_policy;
609         struct sched_param param;
610
611         memset( &param, 0, sizeof(struct sched_param) );
612         if( config_GetType( p_this, "rt-offset" ) )
613         {
614             i_priority += config_GetInt( p_this, "rt-offset" );
615         }
616         if( i_priority <= 0 )
617         {
618             param.sched_priority = (-1) * i_priority;
619             i_policy = SCHED_OTHER;
620         }
621         else
622         {
623             param.sched_priority = i_priority;
624             i_policy = SCHED_RR;
625         }
626         if( (i_error = pthread_setschedparam( p_priv->thread_id,
627                                                i_policy, &param )) )
628         {
629             errno = i_error;
630             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
631                       psz_file, i_line );
632             i_priority = 0;
633         }
634     }
635 #ifndef __APPLE__
636     else
637     {
638         i_priority = 0;
639     }
640 #endif
641
642 #endif
643
644     if( i_ret == 0 )
645     {
646         if( b_wait )
647         {
648             msg_Dbg( p_this, "waiting for thread completion" );
649             vlc_object_wait( p_this );
650         }
651
652         p_priv->b_thread = VLC_TRUE;
653
654 #if defined( WIN32 ) || defined( UNDER_CE )
655         msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
656                  (unsigned int)p_priv->thread_id.id, psz_name,
657          i_priority, psz_file, i_line );
658 #else
659         msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
660                  (unsigned int)p_priv->thread_id, psz_name, i_priority,
661                  psz_file, i_line );
662 #endif
663
664
665         vlc_mutex_unlock( &p_this->object_lock );
666     }
667     else
668     {
669         errno = i_ret;
670         msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
671                          psz_name, psz_file, i_line );
672         vlc_mutex_unlock( &p_this->object_lock );
673     }
674
675     return i_ret;
676 }
677
678 /*****************************************************************************
679  * vlc_thread_set_priority: set the priority of the current thread when we
680  * couldn't set it in vlc_thread_create (for instance for the main thread)
681  *****************************************************************************/
682 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
683                                int i_line, int i_priority )
684 {
685     vlc_object_internals_t *p_priv = p_this->p_internals;
686 #if defined( WIN32 ) || defined( UNDER_CE )
687     if( !p_priv->thread_id.hThread )
688         p_priv->thread_id.hThread = GetCurrentThread();
689     if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
690     {
691         msg_Warn( p_this, "couldn't set a faster priority" );
692         return 1;
693     }
694
695 #elif defined( LIBVLC_USE_PTHREAD )
696 # ifndef __APPLE__
697     if( config_GetInt( p_this, "rt-priority" ) > 0 )
698 # endif
699     {
700         int i_error, i_policy;
701         struct sched_param param;
702
703         memset( &param, 0, sizeof(struct sched_param) );
704         if( config_GetType( p_this, "rt-offset" ) )
705         {
706             i_priority += config_GetInt( p_this, "rt-offset" );
707         }
708         if( i_priority <= 0 )
709         {
710             param.sched_priority = (-1) * i_priority;
711             i_policy = SCHED_OTHER;
712         }
713         else
714         {
715             param.sched_priority = i_priority;
716             i_policy = SCHED_RR;
717         }
718         if( !p_priv->thread_id )
719             p_priv->thread_id = pthread_self();
720         if( (i_error = pthread_setschedparam( p_priv->thread_id,
721                                                i_policy, &param )) )
722         {
723             errno = i_error;
724             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
725                       psz_file, i_line );
726             i_priority = 0;
727         }
728     }
729 #endif
730
731     return 0;
732 }
733
734 /*****************************************************************************
735  * vlc_thread_ready: tell the parent thread we were successfully spawned
736  *****************************************************************************/
737 void __vlc_thread_ready( vlc_object_t *p_this )
738 {
739     vlc_object_signal( p_this );
740 }
741
742 /*****************************************************************************
743  * vlc_thread_join: wait until a thread exits, inner version
744  *****************************************************************************/
745 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
746 {
747     vlc_object_internals_t *p_priv = p_this->p_internals;
748
749 #if defined( UNDER_CE ) || defined( WIN32 )
750     HMODULE hmodule;
751     BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
752                                       FILETIME*, FILETIME* );
753     FILETIME create_ft, exit_ft, kernel_ft, user_ft;
754     int64_t real_time, kernel_time, user_time;
755     HANDLE hThread;
756  
757     /*
758     ** object will close its thread handle when destroyed, duplicate it here
759     ** to be on the safe side
760     */
761     if( ! DuplicateHandle(GetCurrentProcess(),
762             p_priv->thread_id.hThread,
763             GetCurrentProcess(),
764             &hThread,
765             0,
766             FALSE,
767             DUPLICATE_SAME_ACCESS) )
768     {
769         msg_Err( p_this, "thread_join(%u) failed at %s:%d (%s)",
770                          (unsigned int)p_priv->thread_id.id,
771              psz_file, i_line, GetLastError() );
772         p_priv->b_thread = VLC_FALSE;
773         return;
774     }
775
776     WaitForSingleObject( hThread, INFINITE );
777
778     msg_Dbg( p_this, "thread %u joined (%s:%d)",
779              (unsigned int)p_priv->thread_id.id,
780              psz_file, i_line );
781 #if defined( UNDER_CE )
782     hmodule = GetModuleHandle( _T("COREDLL") );
783 #else
784     hmodule = GetModuleHandle( _T("KERNEL32") );
785 #endif
786     OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
787                                          FILETIME*, FILETIME* ))
788         GetProcAddress( hmodule, _T("GetThreadTimes") );
789
790     if( OurGetThreadTimes &&
791         OurGetThreadTimes( hThread,
792                            &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
793     {
794         real_time =
795           ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
796           ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
797         real_time /= 10;
798
799         kernel_time =
800           ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
801            kernel_ft.dwLowDateTime) / 10;
802
803         user_time =
804           ((((int64_t)user_ft.dwHighDateTime)<<32)|
805            user_ft.dwLowDateTime) / 10;
806
807         msg_Dbg( p_this, "thread times: "
808                  "real "I64Fd"m%fs, kernel "I64Fd"m%fs, user "I64Fd"m%fs",
809                  real_time/60/1000000,
810                  (double)((real_time%(60*1000000))/1000000.0),
811                  kernel_time/60/1000000,
812                  (double)((kernel_time%(60*1000000))/1000000.0),
813                  user_time/60/1000000,
814                  (double)((user_time%(60*1000000))/1000000.0) );
815     }
816     CloseHandle( hThread );
817
818 #else /* !defined(WIN32) */
819
820     int i_ret = 0;
821
822 #if defined( HAVE_KERNEL_SCHEDULER_H )
823     int32_t exit_value;
824     i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
825
826 #elif defined( LIBVLC_USE_PTHREAD )
827     i_ret = pthread_join( p_priv->thread_id, NULL );
828
829 #endif
830
831     if( i_ret )
832     {
833         errno = i_ret;
834         msg_Err( p_this, "thread_join(%u) failed at %s:%d (%m)",
835                          (unsigned int)p_priv->thread_id, psz_file, i_line );
836     }
837     else
838     {
839         msg_Dbg( p_this, "thread %u joined (%s:%d)",
840                          (unsigned int)p_priv->thread_id, psz_file, i_line );
841     }
842
843 #endif
844
845     p_priv->b_thread = VLC_FALSE;
846 }
847