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