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