]> git.sesse.net Git - vlc/blob - src/misc/threads.c
Simplify threading code a bit
[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     pthread_mutexattr_t attr;
291     int                 i_result;
292
293     pthread_mutexattr_init( &attr );
294
295 # ifndef NDEBUG
296     /* Create error-checking mutex to detect problems more easily. */
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 # endif
303     i_result = pthread_mutex_init( p_mutex, &attr );
304     pthread_mutexattr_destroy( &attr );
305     return i_result;
306 #endif
307 }
308
309 /*****************************************************************************
310  * vlc_mutex_init: initialize a recursive mutex (Do not use)
311  *****************************************************************************/
312 int __vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
313 {
314 #if defined( WIN32 )
315     /* Create mutex returns a recursive mutex */
316     p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
317     return ( p_mutex->mutex != NULL ? 0 : 1 );
318 #elif defined( LIBVLC_USE_PTHREAD )
319     pthread_mutexattr_t attr;
320     int                 i_result;
321
322     pthread_mutexattr_init( &attr );
323 # ifndef NDEBUG
324     /* Create error-checking mutex to detect problems more easily. */
325 #   if defined(SYS_LINUX)
326     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
327 #   else
328     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
329 #   endif
330 # endif
331     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
332     i_result = pthread_mutex_init( p_mutex, &attr );
333     pthread_mutexattr_destroy( &attr );
334     return( i_result );
335 #else
336 # error Unimplemented!
337 #endif
338 }
339
340
341 /*****************************************************************************
342  * vlc_mutex_destroy: destroy a mutex, inner version
343  *****************************************************************************/
344 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
345 {
346 #if defined( UNDER_CE )
347     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
348
349     DeleteCriticalSection( &p_mutex->csection );
350
351 #elif defined( WIN32 )
352     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
353
354     if( p_mutex->mutex )
355         CloseHandle( p_mutex->mutex );
356     else
357         DeleteCriticalSection( &p_mutex->csection );
358
359 #elif defined( HAVE_KERNEL_SCHEDULER_H )
360     if( p_mutex->init == 9999 )
361         delete_sem( p_mutex->lock );
362
363     p_mutex->init = 0;
364
365 #elif defined( LIBVLC_USE_PTHREAD )
366     int val = pthread_mutex_destroy( p_mutex );
367     VLC_THREAD_ASSERT ("destroying mutex");
368
369 #endif
370 }
371
372 /*****************************************************************************
373  * vlc_cond_init: initialize a condition
374  *****************************************************************************/
375 int __vlc_cond_init( vlc_cond_t *p_condvar )
376 {
377 #if defined( UNDER_CE )
378     /* Initialize counter */
379     p_condvar->i_waiting_threads = 0;
380
381     /* Create an auto-reset event. */
382     p_condvar->event = CreateEvent( NULL,   /* no security */
383                                     FALSE,  /* auto-reset event */
384                                     FALSE,  /* start non-signaled */
385                                     NULL ); /* unnamed */
386     return !p_condvar->event;
387
388 #elif defined( WIN32 )
389     /* Initialize counter */
390     p_condvar->i_waiting_threads = 0;
391
392     /* Misc init */
393     p_condvar->i_win9x_cv = i_win9x_cv;
394
395     if( !b_fast_mutex || p_condvar->i_win9x_cv == 0 )
396     {
397         /* Create an auto-reset event. */
398         p_condvar->event = CreateEvent( NULL,   /* no security */
399                                         FALSE,  /* auto-reset event */
400                                         FALSE,  /* start non-signaled */
401                                         NULL ); /* unnamed */
402
403         p_condvar->semaphore = NULL;
404         return !p_condvar->event;
405     }
406     else
407     {
408         p_condvar->semaphore = CreateSemaphore( NULL,       /* no security */
409                                                 0,          /* initial count */
410                                                 0x7fffffff, /* max count */
411                                                 NULL );     /* unnamed */
412
413         if( p_condvar->i_win9x_cv == 1 )
414             /* Create a manual-reset event initially signaled. */
415             p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
416         else
417             /* Create a auto-reset event. */
418             p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
419
420         InitializeCriticalSection( &p_condvar->csection );
421
422         return !p_condvar->semaphore || !p_condvar->event;
423     }
424
425 #elif defined( HAVE_KERNEL_SCHEDULER_H )
426     if( !p_condvar )
427     {
428         return B_BAD_VALUE;
429     }
430
431     if( p_condvar->init == 9999 )
432     {
433         return EALREADY;
434     }
435
436     p_condvar->thread = -1;
437     p_condvar->init = 9999;
438     return 0;
439
440 #elif defined( LIBVLC_USE_PTHREAD )
441     pthread_condattr_t attr;
442     int ret;
443
444     ret = pthread_condattr_init (&attr);
445     if (ret)
446         return ret;
447
448 # if !defined (_POSIX_CLOCK_SELECTION)
449    /* Fairly outdated POSIX support (that was defined in 2001) */
450 #  define _POSIX_CLOCK_SELECTION (-1)
451 # endif
452 # if (_POSIX_CLOCK_SELECTION >= 0)
453     /* NOTE: This must be the same clock as the one in mtime.c */
454     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
455 # endif
456
457     ret = pthread_cond_init (p_condvar, &attr);
458     pthread_condattr_destroy (&attr);
459     return ret;
460
461 #endif
462 }
463
464 /*****************************************************************************
465  * vlc_cond_destroy: destroy a condition, inner version
466  *****************************************************************************/
467 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
468 {
469 #if defined( UNDER_CE )
470     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
471
472     CloseHandle( p_condvar->event );
473
474 #elif defined( WIN32 )
475     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
476
477     if( !p_condvar->semaphore )
478         CloseHandle( p_condvar->event );
479     else
480     {
481         CloseHandle( p_condvar->event );
482         CloseHandle( p_condvar->semaphore );
483     }
484
485     if( p_condvar->semaphore != NULL )
486         DeleteCriticalSection( &p_condvar->csection );
487
488 #elif defined( HAVE_KERNEL_SCHEDULER_H )
489     p_condvar->init = 0;
490
491 #elif defined( LIBVLC_USE_PTHREAD )
492     int val = pthread_cond_destroy( p_condvar );
493     VLC_THREAD_ASSERT ("destroying condition");
494
495 #endif
496 }
497
498 /*****************************************************************************
499  * vlc_tls_create: create a thread-local variable
500  *****************************************************************************/
501 int __vlc_threadvar_create( vlc_threadvar_t *p_tls )
502 {
503     int i_ret = -1;
504
505 #if defined( HAVE_KERNEL_SCHEDULER_H )
506 # error Unimplemented!
507 #elif defined( UNDER_CE ) || defined( WIN32 )
508 #elif defined( WIN32 )
509     *p_tls = TlsAlloc();
510     i_ret = (*p_tls == INVALID_HANDLE_VALUE) ? EAGAIN : 0;
511
512 #elif defined( LIBVLC_USE_PTHREAD )
513     i_ret =  pthread_key_create( p_tls, NULL );
514 #endif
515     return i_ret;
516 }
517
518 /*****************************************************************************
519  * vlc_thread_create: create a thread, inner version
520  *****************************************************************************
521  * Note that i_priority is only taken into account on platforms supporting
522  * userland real-time priority threads.
523  *****************************************************************************/
524 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
525                          const char *psz_name, void * ( *func ) ( void * ),
526                          int i_priority, bool b_wait )
527 {
528     int i_ret;
529     void *p_data = (void *)p_this;
530     vlc_object_internals_t *p_priv = p_this->p_internals;
531
532     vlc_mutex_lock( &p_this->object_lock );
533
534 #if defined( WIN32 ) || defined( UNDER_CE )
535     {
536         /* When using the MSVCRT C library you have to use the _beginthreadex
537          * function instead of CreateThread, otherwise you'll end up with
538          * memory leaks and the signal functions not working (see Microsoft
539          * Knowledge Base, article 104641) */
540 #if defined( UNDER_CE )
541         DWORD  threadId;
542         HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
543                                       (LPVOID)p_data, CREATE_SUSPENDED,
544                       &threadId );
545 #else
546         unsigned threadId;
547         uintptr_t hThread = _beginthreadex( NULL, 0,
548                         (LPTHREAD_START_ROUTINE)func,
549                                             (void*)p_data, CREATE_SUSPENDED,
550                         &threadId );
551 #endif
552         p_priv->thread_id.id = (DWORD)threadId;
553         p_priv->thread_id.hThread = (HANDLE)hThread;
554         ResumeThread((HANDLE)hThread);
555     }
556
557     i_ret = ( p_priv->thread_id.hThread ? 0 : 1 );
558
559     if( !i_ret && i_priority )
560     {
561         if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
562         {
563             msg_Warn( p_this, "couldn't set a faster priority" );
564             i_priority = 0;
565         }
566     }
567
568 #elif defined( HAVE_KERNEL_SCHEDULER_H )
569     p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
570                                       i_priority, p_data );
571     i_ret = resume_thread( p_priv->thread_id );
572
573 #elif defined( LIBVLC_USE_PTHREAD )
574     i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
575
576 #ifndef __APPLE__
577     if( config_GetInt( p_this, "rt-priority" ) )
578 #endif
579     {
580         int i_error, i_policy;
581         struct sched_param param;
582
583         memset( &param, 0, sizeof(struct sched_param) );
584         if( config_GetType( p_this, "rt-offset" ) )
585         {
586             i_priority += config_GetInt( p_this, "rt-offset" );
587         }
588         if( i_priority <= 0 )
589         {
590             param.sched_priority = (-1) * i_priority;
591             i_policy = SCHED_OTHER;
592         }
593         else
594         {
595             param.sched_priority = i_priority;
596             i_policy = SCHED_RR;
597         }
598         if( (i_error = pthread_setschedparam( p_priv->thread_id,
599                                                i_policy, &param )) )
600         {
601             errno = i_error;
602             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
603                       psz_file, i_line );
604             i_priority = 0;
605         }
606     }
607 #ifndef __APPLE__
608     else
609     {
610         i_priority = 0;
611     }
612 #endif
613
614 #endif
615
616     if( i_ret == 0 )
617     {
618         if( b_wait )
619         {
620             msg_Dbg( p_this, "waiting for thread completion" );
621             vlc_object_wait( p_this );
622         }
623
624         p_priv->b_thread = true;
625
626 #if defined( WIN32 ) || defined( UNDER_CE )
627         msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
628                  (unsigned int)p_priv->thread_id.id, psz_name,
629          i_priority, psz_file, i_line );
630 #else
631         msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
632                  (unsigned int)p_priv->thread_id, psz_name, i_priority,
633                  psz_file, i_line );
634 #endif
635
636
637         vlc_mutex_unlock( &p_this->object_lock );
638     }
639     else
640     {
641         errno = i_ret;
642         msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
643                          psz_name, psz_file, i_line );
644         vlc_mutex_unlock( &p_this->object_lock );
645     }
646
647     return i_ret;
648 }
649
650 /*****************************************************************************
651  * vlc_thread_set_priority: set the priority of the current thread when we
652  * couldn't set it in vlc_thread_create (for instance for the main thread)
653  *****************************************************************************/
654 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
655                                int i_line, int i_priority )
656 {
657     vlc_object_internals_t *p_priv = p_this->p_internals;
658 #if defined( WIN32 ) || defined( UNDER_CE )
659     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
660
661     if( !p_priv->thread_id.hThread )
662         p_priv->thread_id.hThread = GetCurrentThread();
663     if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
664     {
665         msg_Warn( p_this, "couldn't set a faster priority" );
666         return 1;
667     }
668
669 #elif defined( LIBVLC_USE_PTHREAD )
670 # ifndef __APPLE__
671     if( config_GetInt( p_this, "rt-priority" ) > 0 )
672 # endif
673     {
674         int i_error, i_policy;
675         struct sched_param param;
676
677         memset( &param, 0, sizeof(struct sched_param) );
678         if( config_GetType( p_this, "rt-offset" ) )
679         {
680             i_priority += config_GetInt( p_this, "rt-offset" );
681         }
682         if( i_priority <= 0 )
683         {
684             param.sched_priority = (-1) * i_priority;
685             i_policy = SCHED_OTHER;
686         }
687         else
688         {
689             param.sched_priority = i_priority;
690             i_policy = SCHED_RR;
691         }
692         if( !p_priv->thread_id )
693             p_priv->thread_id = pthread_self();
694         if( (i_error = pthread_setschedparam( p_priv->thread_id,
695                                                i_policy, &param )) )
696         {
697             errno = i_error;
698             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
699                       psz_file, i_line );
700             i_priority = 0;
701         }
702     }
703 #endif
704
705     return 0;
706 }
707
708 /*****************************************************************************
709  * vlc_thread_ready: tell the parent thread we were successfully spawned
710  *****************************************************************************/
711 void __vlc_thread_ready( vlc_object_t *p_this )
712 {
713     vlc_object_signal( p_this );
714 }
715
716 /*****************************************************************************
717  * vlc_thread_join: wait until a thread exits, inner version
718  *****************************************************************************/
719 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
720 {
721     vlc_object_internals_t *p_priv = p_this->p_internals;
722
723 #if defined( UNDER_CE ) || defined( WIN32 )
724     HMODULE hmodule;
725     BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
726                                       FILETIME*, FILETIME* );
727     FILETIME create_ft, exit_ft, kernel_ft, user_ft;
728     int64_t real_time, kernel_time, user_time;
729     HANDLE hThread;
730
731     /*
732     ** object will close its thread handle when destroyed, duplicate it here
733     ** to be on the safe side
734     */
735     if( ! DuplicateHandle(GetCurrentProcess(),
736             p_priv->thread_id.hThread,
737             GetCurrentProcess(),
738             &hThread,
739             0,
740             FALSE,
741             DUPLICATE_SAME_ACCESS) )
742     {
743         msg_Err( p_this, "thread_join(%u) failed at %s:%d (%u)",
744                          (unsigned int)p_priv->thread_id.id,
745              psz_file, i_line, (unsigned int)GetLastError() );
746         p_priv->b_thread = false;
747         return;
748     }
749
750     WaitForSingleObject( hThread, INFINITE );
751
752     msg_Dbg( p_this, "thread %u joined (%s:%d)",
753              (unsigned int)p_priv->thread_id.id,
754              psz_file, i_line );
755 #if defined( UNDER_CE )
756     hmodule = GetModuleHandle( _T("COREDLL") );
757 #else
758     hmodule = GetModuleHandle( _T("KERNEL32") );
759 #endif
760     OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
761                                          FILETIME*, FILETIME* ))
762         GetProcAddress( hmodule, _T("GetThreadTimes") );
763
764     if( OurGetThreadTimes &&
765         OurGetThreadTimes( hThread,
766                            &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
767     {
768         real_time =
769           ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
770           ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
771         real_time /= 10;
772
773         kernel_time =
774           ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
775            kernel_ft.dwLowDateTime) / 10;
776
777         user_time =
778           ((((int64_t)user_ft.dwHighDateTime)<<32)|
779            user_ft.dwLowDateTime) / 10;
780
781         msg_Dbg( p_this, "thread times: "
782                  "real "I64Fd"m%fs, kernel "I64Fd"m%fs, user "I64Fd"m%fs",
783                  real_time/60/1000000,
784                  (double)((real_time%(60*1000000))/1000000.0),
785                  kernel_time/60/1000000,
786                  (double)((kernel_time%(60*1000000))/1000000.0),
787                  user_time/60/1000000,
788                  (double)((user_time%(60*1000000))/1000000.0) );
789     }
790     CloseHandle( hThread );
791
792 #else /* !defined(WIN32) */
793
794     int i_ret = 0;
795
796 #if defined( HAVE_KERNEL_SCHEDULER_H )
797     int32_t exit_value;
798     i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
799
800 #elif defined( LIBVLC_USE_PTHREAD )
801     /* Make sure we do return if we are calling vlc_thread_join()
802      * from the joined thread */
803     if (pthread_equal (pthread_self (), p_priv->thread_id))
804         i_ret = pthread_detach (p_priv->thread_id);
805     else
806         i_ret = pthread_join (p_priv->thread_id, NULL);
807 #endif
808
809     if( i_ret )
810     {
811         errno = i_ret;
812         msg_Err( p_this, "thread_join(%u) failed at %s:%d (%m)",
813                          (unsigned int)p_priv->thread_id, psz_file, i_line );
814     }
815     else
816     {
817         msg_Dbg( p_this, "thread %u joined (%s:%d)",
818                          (unsigned int)p_priv->thread_id, psz_file, i_line );
819     }
820
821 #endif
822
823     p_priv->b_thread = false;
824 }
825