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