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