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