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