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