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