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