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