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