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