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