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