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