]> git.sesse.net Git - vlc/blob - src/misc/threads.c
_POSIX_CLOCK_SELECTION at 0 does not mean it's not supported.
[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) && (_POSIX_CLOCK_SELECTION >= 0)
488     /* NOTE: This must be the same clock as the one in mtime.c */
489     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
490 # endif
491
492     ret = pthread_cond_init (&p_condvar->cond, &attr);
493     pthread_condattr_destroy (&attr);
494     return ret;
495
496 #elif defined( HAVE_CTHREADS_H )
497     /* condition_init() */
498     spin_lock_init( &p_condvar->lock );
499     cthread_queue_init( &p_condvar->queue );
500     p_condvar->name = 0;
501     p_condvar->implications = 0;
502
503     return 0;
504
505 #endif
506 }
507
508 /*****************************************************************************
509  * vlc_cond_destroy: destroy a condition, inner version
510  *****************************************************************************/
511 int __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
512 {
513     int i_result;
514     /* In case of error : */
515     int i_thread = -1;
516
517 #if defined( PTH_INIT_IN_PTH_H )
518     return 0;
519
520 #elif defined( ST_INIT_IN_ST_H )
521     i_result = st_cond_destroy( p_condvar->cond );
522
523 #elif defined( UNDER_CE )
524     i_result = !CloseHandle( p_condvar->event );
525
526 #elif defined( WIN32 )
527     if( !p_condvar->semaphore )
528         i_result = !CloseHandle( p_condvar->event );
529     else
530         i_result = !CloseHandle( p_condvar->event )
531           || !CloseHandle( p_condvar->semaphore );
532
533     if( p_condvar->semaphore != NULL )
534         DeleteCriticalSection( &p_condvar->csection );
535
536 #elif defined( HAVE_KERNEL_SCHEDULER_H )
537     p_condvar->init = 0;
538     return 0;
539
540 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
541     i_result = pthread_cond_destroy( &p_condvar->cond );
542     if( i_result )
543     {
544         i_thread = CAST_PTHREAD_TO_INT(pthread_self());
545         errno = i_result;
546     }
547
548 #elif defined( HAVE_CTHREADS_H )
549     return 0;
550
551 #endif
552
553     if( i_result )
554     {
555         msg_Err( p_condvar->p_this,
556                  "thread %d: cond_destroy failed at %s:%d (%d:%m)",
557                  i_thread, psz_file, i_line, i_result );
558         vlc_threads_error( p_condvar->p_this );
559     }
560     return i_result;
561 }
562
563 /*****************************************************************************
564  * vlc_tls_create: create a thread-local variable
565  *****************************************************************************/
566 int __vlc_threadvar_create( vlc_object_t *p_this, vlc_threadvar_t *p_tls )
567 {
568     int i_ret = -1;
569     (void)p_this;
570 #if defined( PTH_INIT_IN_PTH_H )
571     i_ret = pth_key_create( &p_tls->handle, NULL );
572 #elif defined( HAVE_KERNEL_SCHEDULER_H )
573     msg_Err( p_this, "TLS not implemented" );
574     i_ret VLC_EGENERIC;
575 #elif defined( ST_INIT_IN_ST_H )
576     i_ret = st_key_create( &p_tls->handle, NULL );
577 #elif defined( UNDER_CE ) || defined( WIN32 )
578 #elif defined( WIN32 )
579     p_tls->handle = TlsAlloc();
580     i_ret = !( p_tls->handle == 0xFFFFFFFF );
581
582 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
583     i_ret =  pthread_key_create( &p_tls->handle, NULL );
584 #elif defined( HAVE_CTHREADS_H )
585     i_ret = cthread_keycreate( &p_tls-handle );
586 #endif
587     return i_ret;
588 }
589
590 /*****************************************************************************
591  * vlc_thread_create: create a thread, inner version
592  *****************************************************************************
593  * Note that i_priority is only taken into account on platforms supporting
594  * userland real-time priority threads.
595  *****************************************************************************/
596 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
597                          const char *psz_name, void * ( *func ) ( void * ),
598                          int i_priority, vlc_bool_t b_wait )
599 {
600     int i_ret;
601     void *p_data = (void *)p_this;
602     vlc_object_internals_t *p_priv = p_this->p_internals;
603
604     vlc_mutex_lock( &p_this->object_lock );
605
606 #if defined( PTH_INIT_IN_PTH_H )
607     p_priv->thread_id = pth_spawn( PTH_ATTR_DEFAULT, func, p_data );
608     i_ret = p_priv->thread_id == NULL;
609
610 #elif defined( ST_INIT_IN_ST_H )
611     p_priv->thread_id = st_thread_create( func, p_data, 1, 0 );
612     i_ret = 0;
613
614 #elif defined( WIN32 ) || defined( UNDER_CE )
615     {
616         /* When using the MSVCRT C library you have to use the _beginthreadex
617          * function instead of CreateThread, otherwise you'll end up with
618          * memory leaks and the signal functions not working (see Microsoft
619          * Knowledge Base, article 104641) */
620 #if defined( UNDER_CE )
621         DWORD  threadId;
622         HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
623                                       (LPVOID)p_data, CREATE_SUSPENDED,
624                       &threadId );
625 #else
626         unsigned threadId;
627         uintptr_t hThread = _beginthreadex( NULL, 0,
628                         (LPTHREAD_START_ROUTINE)func,
629                                             (void*)p_data, CREATE_SUSPENDED,
630                         &threadId );
631 #endif
632         p_priv->thread_id.id = (DWORD)threadId;
633         p_priv->thread_id.hThread = (HANDLE)hThread;
634     ResumeThread((HANDLE)hThread);
635     }
636
637     i_ret = ( p_priv->thread_id.hThread ? 0 : 1 );
638
639     if( i_ret && i_priority )
640     {
641         if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
642         {
643             msg_Warn( p_this, "couldn't set a faster priority" );
644             i_priority = 0;
645         }
646     }
647
648 #elif defined( HAVE_KERNEL_SCHEDULER_H )
649     p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
650                                       i_priority, p_data );
651     i_ret = resume_thread( p_priv->thread_id );
652
653 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
654     i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
655
656 #ifndef __APPLE__
657     if( config_GetInt( p_this, "rt-priority" ) )
658 #endif
659     {
660         int i_error, i_policy;
661         struct sched_param param;
662
663         memset( &param, 0, sizeof(struct sched_param) );
664         if( config_GetType( p_this, "rt-offset" ) )
665         {
666             i_priority += config_GetInt( p_this, "rt-offset" );
667         }
668         if( i_priority <= 0 )
669         {
670             param.sched_priority = (-1) * i_priority;
671             i_policy = SCHED_OTHER;
672         }
673         else
674         {
675             param.sched_priority = i_priority;
676             i_policy = SCHED_RR;
677         }
678         if( (i_error = pthread_setschedparam( p_priv->thread_id,
679                                                i_policy, &param )) )
680         {
681             errno = i_error;
682             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
683                       psz_file, i_line );
684             i_priority = 0;
685         }
686     }
687 #ifndef __APPLE__
688     else
689     {
690         i_priority = 0;
691     }
692 #endif
693
694 #elif defined( HAVE_CTHREADS_H )
695     p_priv->thread_id = cthread_fork( (cthread_fn_t)func, (any_t)p_data );
696     i_ret = 0;
697
698 #endif
699
700     if( i_ret == 0 )
701     {
702         if( b_wait )
703         {
704             msg_Dbg( p_this, "waiting for thread completion" );
705             vlc_object_wait( p_this );
706         }
707
708         p_priv->b_thread = VLC_TRUE;
709
710 #if defined( WIN32 ) || defined( UNDER_CE )
711         msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
712                  (unsigned int)p_priv->thread_id.id, psz_name,
713          i_priority, psz_file, i_line );
714 #else
715         msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
716                  (unsigned int)p_priv->thread_id, psz_name, i_priority,
717                  psz_file, i_line );
718 #endif
719
720
721         vlc_mutex_unlock( &p_this->object_lock );
722     }
723     else
724     {
725         errno = i_ret;
726         msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
727                          psz_name, psz_file, i_line );
728         vlc_threads_error( p_this );
729         vlc_mutex_unlock( &p_this->object_lock );
730     }
731
732     return i_ret;
733 }
734
735 /*****************************************************************************
736  * vlc_thread_set_priority: set the priority of the current thread when we
737  * couldn't set it in vlc_thread_create (for instance for the main thread)
738  *****************************************************************************/
739 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
740                                int i_line, int i_priority )
741 {
742     vlc_object_internals_t *p_priv = p_this->p_internals;
743 #if defined( PTH_INIT_IN_PTH_H ) || defined( ST_INIT_IN_ST_H )
744 #elif defined( WIN32 ) || defined( UNDER_CE )
745     if( !p_priv->thread_id.hThread )
746         p_priv->thread_id.hThread = GetCurrentThread();
747     if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
748     {
749         msg_Warn( p_this, "couldn't set a faster priority" );
750         return 1;
751     }
752
753 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
754 # ifndef __APPLE__
755     if( config_GetInt( p_this, "rt-priority" ) > 0 )
756 # endif
757     {
758         int i_error, i_policy;
759         struct sched_param param;
760
761         memset( &param, 0, sizeof(struct sched_param) );
762         if( config_GetType( p_this, "rt-offset" ) )
763         {
764             i_priority += config_GetInt( p_this, "rt-offset" );
765         }
766         if( i_priority <= 0 )
767         {
768             param.sched_priority = (-1) * i_priority;
769             i_policy = SCHED_OTHER;
770         }
771         else
772         {
773             param.sched_priority = i_priority;
774             i_policy = SCHED_RR;
775         }
776         if( !p_priv->thread_id )
777             p_priv->thread_id = pthread_self();
778         if( (i_error = pthread_setschedparam( p_priv->thread_id,
779                                                i_policy, &param )) )
780         {
781             errno = i_error;
782             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
783                       psz_file, i_line );
784             i_priority = 0;
785         }
786     }
787 #endif
788
789     return 0;
790 }
791
792 /*****************************************************************************
793  * vlc_thread_ready: tell the parent thread we were successfully spawned
794  *****************************************************************************/
795 void __vlc_thread_ready( vlc_object_t *p_this )
796 {
797     vlc_object_signal( p_this );
798 }
799
800 /*****************************************************************************
801  * vlc_thread_join: wait until a thread exits, inner version
802  *****************************************************************************/
803 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
804 {
805     vlc_object_internals_t *p_priv = p_this->p_internals;
806
807 #if defined( UNDER_CE ) || defined( WIN32 )
808     HMODULE hmodule;
809     BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
810                                       FILETIME*, FILETIME* );
811     FILETIME create_ft, exit_ft, kernel_ft, user_ft;
812     int64_t real_time, kernel_time, user_time;
813     HANDLE hThread;
814  
815     /*
816     ** object will close its thread handle when destroyed, duplicate it here
817     ** to be on the safe side
818     */
819     if( ! DuplicateHandle(GetCurrentProcess(),
820             p_priv->thread_id.hThread,
821             GetCurrentProcess(),
822             &hThread,
823             0,
824             FALSE,
825             DUPLICATE_SAME_ACCESS) )
826     {
827         msg_Err( p_this, "thread_join(%u) failed at %s:%d (%s)",
828                          (unsigned int)p_priv->thread_id.id,
829              psz_file, i_line, GetLastError() );
830         vlc_threads_error( p_this );
831         p_priv->b_thread = VLC_FALSE;
832         return;
833     }
834
835     WaitForSingleObject( hThread, INFINITE );
836
837     msg_Dbg( p_this, "thread %u joined (%s:%d)",
838              (unsigned int)p_priv->thread_id.id,
839              psz_file, i_line );
840 #if defined( UNDER_CE )
841     hmodule = GetModuleHandle( _T("COREDLL") );
842 #else
843     hmodule = GetModuleHandle( _T("KERNEL32") );
844 #endif
845     OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
846                                          FILETIME*, FILETIME* ))
847         GetProcAddress( hmodule, _T("GetThreadTimes") );
848
849     if( OurGetThreadTimes &&
850         OurGetThreadTimes( hThread,
851                            &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
852     {
853         real_time =
854           ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
855           ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
856         real_time /= 10;
857
858         kernel_time =
859           ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
860            kernel_ft.dwLowDateTime) / 10;
861
862         user_time =
863           ((((int64_t)user_ft.dwHighDateTime)<<32)|
864            user_ft.dwLowDateTime) / 10;
865
866         msg_Dbg( p_this, "thread times: "
867                  "real "I64Fd"m%fs, kernel "I64Fd"m%fs, user "I64Fd"m%fs",
868                  real_time/60/1000000,
869                  (double)((real_time%(60*1000000))/1000000.0),
870                  kernel_time/60/1000000,
871                  (double)((kernel_time%(60*1000000))/1000000.0),
872                  user_time/60/1000000,
873                  (double)((user_time%(60*1000000))/1000000.0) );
874     }
875     CloseHandle( hThread );
876
877 #else /* !defined(WIN32) */
878
879     int i_ret = 0;
880
881 #if defined( PTH_INIT_IN_PTH_H )
882     i_ret = ( pth_join( p_priv->thread_id, NULL ) == FALSE );
883
884 #elif defined( ST_INIT_IN_ST_H )
885     i_ret = st_thread_join( p_priv->thread_id, NULL );
886
887 #elif defined( HAVE_KERNEL_SCHEDULER_H )
888     int32_t exit_value;
889     i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
890
891 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
892     i_ret = pthread_join( p_priv->thread_id, NULL );
893
894 #elif defined( HAVE_CTHREADS_H )
895     cthread_join( p_priv->thread_id );
896     i_ret = 1;
897
898 #endif
899
900     if( i_ret )
901     {
902         errno = i_ret;
903         msg_Err( p_this, "thread_join(%u) failed at %s:%d (%m)",
904                          (unsigned int)p_priv->thread_id, psz_file, i_line );
905         vlc_threads_error( p_this );
906     }
907     else
908     {
909         msg_Dbg( p_this, "thread %u joined (%s:%d)",
910                          (unsigned int)p_priv->thread_id, psz_file, i_line );
911     }
912
913 #endif
914
915     p_priv->b_thread = VLC_FALSE;
916 }
917