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