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