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