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