]> git.sesse.net Git - vlc/blob - src/misc/threads.c
Win32 threads: Set priority on success rather than failure.
[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( LIBVLC_USE_PTHREAD )
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( LIBVLC_USE_PTHREAD )
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( LIBVLC_USE_PTHREAD )
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( LIBVLC_USE_PTHREAD )
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( LIBVLC_USE_PTHREAD )
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( LIBVLC_USE_PTHREAD )
223     pthread_mutex_unlock( &once_mutex );
224 #endif
225     return VLC_SUCCESS;
226 }
227
228 #ifdef __linux__
229 /* This is not prototyped under Linux, though it exists. */
230 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
231 #endif
232
233 /*****************************************************************************
234  * vlc_mutex_init: initialize a mutex
235  *****************************************************************************/
236 int __vlc_mutex_init( vlc_object_t *p_this, vlc_mutex_t *p_mutex )
237 {
238     p_mutex->p_this = p_this;
239
240 #if defined( UNDER_CE )
241     InitializeCriticalSection( &p_mutex->csection );
242     return 0;
243
244 #elif defined( WIN32 )
245     /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
246      * function and have a 100% correct vlc_cond_wait() implementation.
247      * As this function is not available on Win9x, we can use the faster
248      * CriticalSections */
249     if( pf_SignalObjectAndWait && !b_fast_mutex )
250     {
251         /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
252         p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
253         return ( p_mutex->mutex != NULL ? 0 : 1 );
254     }
255     else
256     {
257         p_mutex->mutex = NULL;
258         InitializeCriticalSection( &p_mutex->csection );
259         return 0;
260     }
261
262 #elif defined( HAVE_KERNEL_SCHEDULER_H )
263     /* check the arguments and whether it's already been initialized */
264     if( p_mutex == NULL )
265     {
266         return B_BAD_VALUE;
267     }
268
269     if( p_mutex->init == 9999 )
270     {
271         return EALREADY;
272     }
273
274     p_mutex->lock = create_sem( 1, "BeMutex" );
275     if( p_mutex->lock < B_NO_ERROR )
276     {
277         return( -1 );
278     }
279
280     p_mutex->init = 9999;
281     return B_OK;
282
283 #elif defined( LIBVLC_USE_PTHREAD )
284 # ifndef NDEBUG
285     {
286         /* Create error-checking mutex to detect problems more easily. */
287         pthread_mutexattr_t attr;
288         int                 i_result;
289
290         pthread_mutexattr_init( &attr );
291 #   if defined(SYS_LINUX)
292         pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
293 #   else
294         pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
295 #   endif
296
297         i_result = pthread_mutex_init( &p_mutex->mutex, &attr );
298         pthread_mutexattr_destroy( &attr );
299         return( i_result );
300     }
301 # endif /* NDEBUG */
302     return pthread_mutex_init( &p_mutex->mutex, NULL );
303
304 #endif
305 }
306
307 /*****************************************************************************
308  * vlc_mutex_init: initialize a recursive mutex (Do not use)
309  *****************************************************************************/
310 int __vlc_mutex_init_recursive( vlc_object_t *p_this, vlc_mutex_t *p_mutex )
311 {
312 #if defined( WIN32 )
313     /* Create mutex returns a recursive mutex */
314     p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
315     return ( p_mutex->mutex != NULL ? 0 : 1 );
316 #elif defined( LIBVLC_USE_PTHREAD )
317     pthread_mutexattr_t attr;
318     int                 i_result;
319
320     pthread_mutexattr_init( &attr );
321 # ifndef NDEBUG
322     /* Create error-checking mutex to detect problems more easily. */
323 #   if defined(SYS_LINUX)
324     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
325 #   else
326     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
327 #   endif
328 # endif
329     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
330     i_result = pthread_mutex_init( &p_mutex->mutex, &attr );
331     pthread_mutexattr_destroy( &attr );
332     return( i_result );
333 #else
334     msg_Err(p_this, "no recursive mutex found. Falling back to regular mutex.\n"
335                     "Expect hangs\n")
336     return __vlc_mutex_init( p_this, p_mutex );
337 #endif
338 }
339
340
341 /*****************************************************************************
342  * vlc_mutex_destroy: destroy a mutex, inner version
343  *****************************************************************************/
344 int __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
345 {
346     int i_result;
347     /* In case of error : */
348     int i_thread = -1;
349
350 #if defined( UNDER_CE )
351     DeleteCriticalSection( &p_mutex->csection );
352     return 0;
353
354 #elif defined( WIN32 )
355     if( p_mutex->mutex )
356     {
357         CloseHandle( p_mutex->mutex );
358     }
359     else
360     {
361         DeleteCriticalSection( &p_mutex->csection );
362     }
363     return 0;
364
365 #elif defined( HAVE_KERNEL_SCHEDULER_H )
366     if( p_mutex->init == 9999 )
367     {
368         delete_sem( p_mutex->lock );
369     }
370
371     p_mutex->init = 0;
372     return B_OK;
373
374 #elif defined( LIBVLC_USE_PTHREAD )
375     i_result = pthread_mutex_destroy( &p_mutex->mutex );
376     if( i_result )
377     {
378         i_thread = CAST_PTHREAD_TO_INT(pthread_self());
379         errno = i_result;
380     }
381
382 #endif
383
384     if( i_result )
385     {
386         msg_Err( p_mutex->p_this,
387                  "thread %d: mutex_destroy failed at %s:%d (%d:%m)",
388                  i_thread, psz_file, i_line, i_result );
389         vlc_threads_error( p_mutex->p_this );
390     }
391     return i_result;
392 }
393
394 /*****************************************************************************
395  * vlc_cond_init: initialize a condition
396  *****************************************************************************/
397 int __vlc_cond_init( vlc_object_t *p_this, vlc_cond_t *p_condvar )
398 {
399     p_condvar->p_this = p_this;
400
401 #if defined( UNDER_CE )
402     /* Initialize counter */
403     p_condvar->i_waiting_threads = 0;
404
405     /* Create an auto-reset event. */
406     p_condvar->event = CreateEvent( NULL,   /* no security */
407                                     FALSE,  /* auto-reset event */
408                                     FALSE,  /* start non-signaled */
409                                     NULL ); /* unnamed */
410     return !p_condvar->event;
411
412 #elif defined( WIN32 )
413     /* Initialize counter */
414     p_condvar->i_waiting_threads = 0;
415
416     /* Misc init */
417     p_condvar->i_win9x_cv = i_win9x_cv;
418     p_condvar->SignalObjectAndWait = pf_SignalObjectAndWait;
419
420     if( (p_condvar->SignalObjectAndWait && !b_fast_mutex)
421         || p_condvar->i_win9x_cv == 0 )
422     {
423         /* Create an auto-reset event. */
424         p_condvar->event = CreateEvent( NULL,   /* no security */
425                                         FALSE,  /* auto-reset event */
426                                         FALSE,  /* start non-signaled */
427                                         NULL ); /* unnamed */
428
429         p_condvar->semaphore = NULL;
430         return !p_condvar->event;
431     }
432     else
433     {
434         p_condvar->semaphore = CreateSemaphore( NULL,       /* no security */
435                                                 0,          /* initial count */
436                                                 0x7fffffff, /* max count */
437                                                 NULL );     /* unnamed */
438
439         if( p_condvar->i_win9x_cv == 1 )
440             /* Create a manual-reset event initially signaled. */
441             p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
442         else
443             /* Create a auto-reset event. */
444             p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
445
446         InitializeCriticalSection( &p_condvar->csection );
447
448         return !p_condvar->semaphore || !p_condvar->event;
449     }
450
451 #elif defined( HAVE_KERNEL_SCHEDULER_H )
452     if( !p_condvar )
453     {
454         return B_BAD_VALUE;
455     }
456
457     if( p_condvar->init == 9999 )
458     {
459         return EALREADY;
460     }
461
462     p_condvar->thread = -1;
463     p_condvar->init = 9999;
464     return 0;
465
466 #elif defined( LIBVLC_USE_PTHREAD )
467     pthread_condattr_t attr;
468     int ret;
469
470     ret = pthread_condattr_init (&attr);
471     if (ret)
472         return ret;
473
474 # if !defined (_POSIX_CLOCK_SELECTION)
475    /* Fairly outdated POSIX support (that was defined in 2001) */
476 #  define _POSIX_CLOCK_SELECTION (-1)
477 # endif
478 # if (_POSIX_CLOCK_SELECTION >= 0)
479     /* NOTE: This must be the same clock as the one in mtime.c */
480     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
481 # endif
482
483     ret = pthread_cond_init (&p_condvar->cond, &attr);
484     pthread_condattr_destroy (&attr);
485     return ret;
486
487 #endif
488 }
489
490 /*****************************************************************************
491  * vlc_cond_destroy: destroy a condition, inner version
492  *****************************************************************************/
493 int __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
494 {
495     int i_result;
496     /* In case of error : */
497     int i_thread = -1;
498
499 #if defined( UNDER_CE )
500     i_result = !CloseHandle( p_condvar->event );
501
502 #elif defined( WIN32 )
503     if( !p_condvar->semaphore )
504         i_result = !CloseHandle( p_condvar->event );
505     else
506         i_result = !CloseHandle( p_condvar->event )
507           || !CloseHandle( p_condvar->semaphore );
508
509     if( p_condvar->semaphore != NULL )
510         DeleteCriticalSection( &p_condvar->csection );
511
512 #elif defined( HAVE_KERNEL_SCHEDULER_H )
513     p_condvar->init = 0;
514     return 0;
515
516 #elif defined( LIBVLC_USE_PTHREAD )
517     i_result = pthread_cond_destroy( &p_condvar->cond );
518     if( i_result )
519     {
520         i_thread = CAST_PTHREAD_TO_INT(pthread_self());
521         errno = i_result;
522     }
523
524 #endif
525
526     if( i_result )
527     {
528         msg_Err( p_condvar->p_this,
529                  "thread %d: cond_destroy failed at %s:%d (%d:%m)",
530                  i_thread, psz_file, i_line, i_result );
531         vlc_threads_error( p_condvar->p_this );
532     }
533     return i_result;
534 }
535
536 /*****************************************************************************
537  * vlc_tls_create: create a thread-local variable
538  *****************************************************************************/
539 int __vlc_threadvar_create( vlc_object_t *p_this, vlc_threadvar_t *p_tls )
540 {
541     int i_ret = -1;
542     (void)p_this;
543
544 #if defined( HAVE_KERNEL_SCHEDULER_H )
545     msg_Err( p_this, "TLS not implemented" );
546     i_ret VLC_EGENERIC;
547 #elif defined( UNDER_CE ) || defined( WIN32 )
548 #elif defined( WIN32 )
549     p_tls->handle = TlsAlloc();
550     i_ret = !( p_tls->handle == 0xFFFFFFFF );
551
552 #elif defined( LIBVLC_USE_PTHREAD )
553     i_ret =  pthread_key_create( &p_tls->handle, NULL );
554 #endif
555     return i_ret;
556 }
557
558 /*****************************************************************************
559  * vlc_thread_create: create a thread, inner version
560  *****************************************************************************
561  * Note that i_priority is only taken into account on platforms supporting
562  * userland real-time priority threads.
563  *****************************************************************************/
564 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
565                          const char *psz_name, void * ( *func ) ( void * ),
566                          int i_priority, vlc_bool_t b_wait )
567 {
568     int i_ret;
569     void *p_data = (void *)p_this;
570     vlc_object_internals_t *p_priv = p_this->p_internals;
571
572     vlc_mutex_lock( &p_this->object_lock );
573
574 #if defined( WIN32 ) || defined( UNDER_CE )
575     {
576         /* When using the MSVCRT C library you have to use the _beginthreadex
577          * function instead of CreateThread, otherwise you'll end up with
578          * memory leaks and the signal functions not working (see Microsoft
579          * Knowledge Base, article 104641) */
580 #if defined( UNDER_CE )
581         DWORD  threadId;
582         HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
583                                       (LPVOID)p_data, CREATE_SUSPENDED,
584                       &threadId );
585 #else
586         unsigned threadId;
587         uintptr_t hThread = _beginthreadex( NULL, 0,
588                         (LPTHREAD_START_ROUTINE)func,
589                                             (void*)p_data, CREATE_SUSPENDED,
590                         &threadId );
591 #endif
592         p_priv->thread_id.id = (DWORD)threadId;
593         p_priv->thread_id.hThread = (HANDLE)hThread;
594         ResumeThread((HANDLE)hThread);
595     }
596
597     i_ret = ( p_priv->thread_id.hThread ? 0 : 1 );
598
599     if( !i_ret && i_priority )
600     {
601         if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
602         {
603             msg_Warn( p_this, "couldn't set a faster priority" );
604             i_priority = 0;
605         }
606     }
607
608 #elif defined( HAVE_KERNEL_SCHEDULER_H )
609     p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
610                                       i_priority, p_data );
611     i_ret = resume_thread( p_priv->thread_id );
612
613 #elif defined( LIBVLC_USE_PTHREAD )
614     i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
615
616 #ifndef __APPLE__
617     if( config_GetInt( p_this, "rt-priority" ) )
618 #endif
619     {
620         int i_error, i_policy;
621         struct sched_param param;
622
623         memset( &param, 0, sizeof(struct sched_param) );
624         if( config_GetType( p_this, "rt-offset" ) )
625         {
626             i_priority += config_GetInt( p_this, "rt-offset" );
627         }
628         if( i_priority <= 0 )
629         {
630             param.sched_priority = (-1) * i_priority;
631             i_policy = SCHED_OTHER;
632         }
633         else
634         {
635             param.sched_priority = i_priority;
636             i_policy = SCHED_RR;
637         }
638         if( (i_error = pthread_setschedparam( p_priv->thread_id,
639                                                i_policy, &param )) )
640         {
641             errno = i_error;
642             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
643                       psz_file, i_line );
644             i_priority = 0;
645         }
646     }
647 #ifndef __APPLE__
648     else
649     {
650         i_priority = 0;
651     }
652 #endif
653
654 #endif
655
656     if( i_ret == 0 )
657     {
658         if( b_wait )
659         {
660             msg_Dbg( p_this, "waiting for thread completion" );
661             vlc_object_wait( p_this );
662         }
663
664         p_priv->b_thread = VLC_TRUE;
665
666 #if defined( WIN32 ) || defined( UNDER_CE )
667         msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
668                  (unsigned int)p_priv->thread_id.id, psz_name,
669          i_priority, psz_file, i_line );
670 #else
671         msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
672                  (unsigned int)p_priv->thread_id, psz_name, i_priority,
673                  psz_file, i_line );
674 #endif
675
676
677         vlc_mutex_unlock( &p_this->object_lock );
678     }
679     else
680     {
681         errno = i_ret;
682         msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
683                          psz_name, psz_file, i_line );
684         vlc_threads_error( p_this );
685         vlc_mutex_unlock( &p_this->object_lock );
686     }
687
688     return i_ret;
689 }
690
691 /*****************************************************************************
692  * vlc_thread_set_priority: set the priority of the current thread when we
693  * couldn't set it in vlc_thread_create (for instance for the main thread)
694  *****************************************************************************/
695 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
696                                int i_line, int i_priority )
697 {
698     vlc_object_internals_t *p_priv = p_this->p_internals;
699 #if defined( WIN32 ) || defined( UNDER_CE )
700     if( !p_priv->thread_id.hThread )
701         p_priv->thread_id.hThread = GetCurrentThread();
702     if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
703     {
704         msg_Warn( p_this, "couldn't set a faster priority" );
705         return 1;
706     }
707
708 #elif defined( LIBVLC_USE_PTHREAD )
709 # ifndef __APPLE__
710     if( config_GetInt( p_this, "rt-priority" ) > 0 )
711 # endif
712     {
713         int i_error, i_policy;
714         struct sched_param param;
715
716         memset( &param, 0, sizeof(struct sched_param) );
717         if( config_GetType( p_this, "rt-offset" ) )
718         {
719             i_priority += config_GetInt( p_this, "rt-offset" );
720         }
721         if( i_priority <= 0 )
722         {
723             param.sched_priority = (-1) * i_priority;
724             i_policy = SCHED_OTHER;
725         }
726         else
727         {
728             param.sched_priority = i_priority;
729             i_policy = SCHED_RR;
730         }
731         if( !p_priv->thread_id )
732             p_priv->thread_id = pthread_self();
733         if( (i_error = pthread_setschedparam( p_priv->thread_id,
734                                                i_policy, &param )) )
735         {
736             errno = i_error;
737             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
738                       psz_file, i_line );
739             i_priority = 0;
740         }
741     }
742 #endif
743
744     return 0;
745 }
746
747 /*****************************************************************************
748  * vlc_thread_ready: tell the parent thread we were successfully spawned
749  *****************************************************************************/
750 void __vlc_thread_ready( vlc_object_t *p_this )
751 {
752     vlc_object_signal( p_this );
753 }
754
755 /*****************************************************************************
756  * vlc_thread_join: wait until a thread exits, inner version
757  *****************************************************************************/
758 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
759 {
760     vlc_object_internals_t *p_priv = p_this->p_internals;
761
762 #if defined( UNDER_CE ) || defined( WIN32 )
763     HMODULE hmodule;
764     BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
765                                       FILETIME*, FILETIME* );
766     FILETIME create_ft, exit_ft, kernel_ft, user_ft;
767     int64_t real_time, kernel_time, user_time;
768     HANDLE hThread;
769  
770     /*
771     ** object will close its thread handle when destroyed, duplicate it here
772     ** to be on the safe side
773     */
774     if( ! DuplicateHandle(GetCurrentProcess(),
775             p_priv->thread_id.hThread,
776             GetCurrentProcess(),
777             &hThread,
778             0,
779             FALSE,
780             DUPLICATE_SAME_ACCESS) )
781     {
782         msg_Err( p_this, "thread_join(%u) failed at %s:%d (%s)",
783                          (unsigned int)p_priv->thread_id.id,
784              psz_file, i_line, GetLastError() );
785         vlc_threads_error( p_this );
786         p_priv->b_thread = VLC_FALSE;
787         return;
788     }
789
790     WaitForSingleObject( hThread, INFINITE );
791
792     msg_Dbg( p_this, "thread %u joined (%s:%d)",
793              (unsigned int)p_priv->thread_id.id,
794              psz_file, i_line );
795 #if defined( UNDER_CE )
796     hmodule = GetModuleHandle( _T("COREDLL") );
797 #else
798     hmodule = GetModuleHandle( _T("KERNEL32") );
799 #endif
800     OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
801                                          FILETIME*, FILETIME* ))
802         GetProcAddress( hmodule, _T("GetThreadTimes") );
803
804     if( OurGetThreadTimes &&
805         OurGetThreadTimes( hThread,
806                            &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
807     {
808         real_time =
809           ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
810           ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
811         real_time /= 10;
812
813         kernel_time =
814           ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
815            kernel_ft.dwLowDateTime) / 10;
816
817         user_time =
818           ((((int64_t)user_ft.dwHighDateTime)<<32)|
819            user_ft.dwLowDateTime) / 10;
820
821         msg_Dbg( p_this, "thread times: "
822                  "real "I64Fd"m%fs, kernel "I64Fd"m%fs, user "I64Fd"m%fs",
823                  real_time/60/1000000,
824                  (double)((real_time%(60*1000000))/1000000.0),
825                  kernel_time/60/1000000,
826                  (double)((kernel_time%(60*1000000))/1000000.0),
827                  user_time/60/1000000,
828                  (double)((user_time%(60*1000000))/1000000.0) );
829     }
830     CloseHandle( hThread );
831
832 #else /* !defined(WIN32) */
833
834     int i_ret = 0;
835
836 #if defined( HAVE_KERNEL_SCHEDULER_H )
837     int32_t exit_value;
838     i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
839
840 #elif defined( LIBVLC_USE_PTHREAD )
841     i_ret = pthread_join( p_priv->thread_id, NULL );
842
843 #endif
844
845     if( i_ret )
846     {
847         errno = i_ret;
848         msg_Err( p_this, "thread_join(%u) failed at %s:%d (%m)",
849                          (unsigned int)p_priv->thread_id, psz_file, i_line );
850         vlc_threads_error( p_this );
851     }
852     else
853     {
854         msg_Dbg( p_this, "thread %u joined (%s:%d)",
855                          (unsigned int)p_priv->thread_id, psz_file, i_line );
856     }
857
858 #endif
859
860     p_priv->b_thread = VLC_FALSE;
861 }
862