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