]> git.sesse.net Git - vlc/blob - include/vlc_threads.h
Rescale POSIX realtime priorities within a portable range
[vlc] / include / vlc_threads.h
1 /*****************************************************************************
2  * vlc_threads.h : threads implementation for the VideoLAN client
3  * This header provides portable declarations for mutexes & conditions
4  *****************************************************************************
5  * Copyright (C) 1999, 2002 the VideoLAN team
6  * $Id$
7  *
8  * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
9  *          Samuel Hocevar <sam@via.ecp.fr>
10  *          Gildas Bazin <gbazin@netcourrier.com>
11  *          Christophe Massiot <massiot@via.ecp.fr>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 #if !defined( __LIBVLC__ )
29   #error You are not libvlc or one of its plugins. You cannot include this file
30 #endif
31
32 #ifndef _VLC_THREADS_H_
33 #define _VLC_THREADS_H_
34
35 #if defined( UNDER_CE )
36                                                                 /* WinCE API */
37 #elif defined( WIN32 )
38 #   include <process.h>                                         /* Win32 API */
39 #   include <errno.h>
40
41 #elif defined( SYS_BEOS )                                            /* BeOS */
42 #   include <kernel/OS.h>
43 #   include <kernel/scheduler.h>
44 #   include <byteorder.h>
45
46 #else                                         /* pthreads (like Linux & BSD) */
47 #   define LIBVLC_USE_PTHREAD 1
48 #   define _APPLE_C_SOURCE    1 /* Proper pthread semantics on OSX */
49
50 #   include <stdlib.h> /* lldiv_t definition (only in C99) */
51 #   include <unistd.h> /* _POSIX_SPIN_LOCKS */
52 #   include <pthread.h>
53     /* Needed for pthread_cond_timedwait */
54 #   include <errno.h>
55 #   include <time.h>
56
57 #endif
58
59 /*****************************************************************************
60  * Constants
61  *****************************************************************************/
62
63 /* Thread priorities */
64 #ifdef __APPLE__
65 #   define VLC_THREAD_PRIORITY_LOW (-47)
66 #   define VLC_THREAD_PRIORITY_INPUT 37
67 #   define VLC_THREAD_PRIORITY_AUDIO 37
68 #   define VLC_THREAD_PRIORITY_VIDEO (-47)
69 #   define VLC_THREAD_PRIORITY_OUTPUT 37
70 #   define VLC_THREAD_PRIORITY_HIGHEST 37
71
72 #elif defined(SYS_BEOS)
73 #   define VLC_THREAD_PRIORITY_LOW 5
74 #   define VLC_THREAD_PRIORITY_INPUT 10
75 #   define VLC_THREAD_PRIORITY_AUDIO 10
76 #   define VLC_THREAD_PRIORITY_VIDEO 5
77 #   define VLC_THREAD_PRIORITY_OUTPUT 15
78 #   define VLC_THREAD_PRIORITY_HIGHEST 15
79
80 #elif defined(LIBVLC_USE_PTHREAD)
81 #   define VLC_THREAD_PRIORITY_LOW      0
82 #   define VLC_THREAD_PRIORITY_INPUT   10
83 #   define VLC_THREAD_PRIORITY_AUDIO    5
84 #   define VLC_THREAD_PRIORITY_VIDEO    0
85 #   define VLC_THREAD_PRIORITY_OUTPUT  15
86 #   define VLC_THREAD_PRIORITY_HIGHEST 20
87
88 #elif defined(WIN32) || defined(UNDER_CE)
89 /* Define different priorities for WinNT/2K/XP and Win9x/Me */
90 #   define VLC_THREAD_PRIORITY_LOW 0
91 #   define VLC_THREAD_PRIORITY_INPUT \
92         (IS_WINNT ? THREAD_PRIORITY_ABOVE_NORMAL : 0)
93 #   define VLC_THREAD_PRIORITY_AUDIO \
94         (IS_WINNT ? THREAD_PRIORITY_HIGHEST : 0)
95 #   define VLC_THREAD_PRIORITY_VIDEO \
96         (IS_WINNT ? 0 : THREAD_PRIORITY_BELOW_NORMAL )
97 #   define VLC_THREAD_PRIORITY_OUTPUT \
98         (IS_WINNT ? THREAD_PRIORITY_ABOVE_NORMAL : 0)
99 #   define VLC_THREAD_PRIORITY_HIGHEST \
100         (IS_WINNT ? THREAD_PRIORITY_TIME_CRITICAL : 0)
101
102 #else
103 #   define VLC_THREAD_PRIORITY_LOW 0
104 #   define VLC_THREAD_PRIORITY_INPUT 0
105 #   define VLC_THREAD_PRIORITY_AUDIO 0
106 #   define VLC_THREAD_PRIORITY_VIDEO 0
107 #   define VLC_THREAD_PRIORITY_OUTPUT 0
108 #   define VLC_THREAD_PRIORITY_HIGHEST 0
109
110 #endif
111
112 /*****************************************************************************
113  * Type definitions
114  *****************************************************************************/
115
116 #if defined (LIBVLC_USE_PTHREAD)
117 typedef pthread_t       vlc_thread_t;
118 typedef pthread_mutex_t vlc_mutex_t;
119 typedef pthread_cond_t  vlc_cond_t;
120 typedef pthread_key_t   vlc_threadvar_t;
121
122 #elif defined( WIN32 ) || defined( UNDER_CE )
123 typedef HANDLE  vlc_thread_t;
124
125 typedef BOOL (WINAPI *SIGNALOBJECTANDWAIT) ( HANDLE, HANDLE, DWORD, BOOL );
126
127 typedef HANDLE  vlc_mutex_t;
128
129 typedef struct
130 {
131     volatile int        i_waiting_threads;
132     HANDLE              event;
133 } vlc_cond_t;
134
135 typedef DWORD   vlc_threadvar_t;
136
137 #elif defined( SYS_BEOS )
138 /* This is the BeOS implementation of the vlc threads, note that the mutex is
139  * not a real mutex and the cond_var is not like a pthread cond_var but it is
140  * enough for what we need */
141
142 typedef thread_id vlc_thread_t;
143
144 typedef struct
145 {
146     int32_t         init;
147     sem_id          lock;
148 } vlc_mutex_t;
149
150 typedef struct
151 {
152     int32_t         init;
153     thread_id       thread;
154 } vlc_cond_t;
155
156 typedef struct
157 {
158 } vlc_threadvar_t;
159
160 #endif
161
162 #if defined( WIN32 ) && !defined ETIMEDOUT
163 #  define ETIMEDOUT 10060 /* This is the value in winsock.h. */
164 #endif
165
166 /*****************************************************************************
167  * Function definitions
168  *****************************************************************************/
169 VLC_EXPORT( int,  vlc_mutex_init,    ( vlc_mutex_t * ) );
170 VLC_EXPORT( int,  vlc_mutex_init_recursive, ( vlc_mutex_t * ) );
171 VLC_EXPORT( void,  __vlc_mutex_destroy, ( const char *, int, vlc_mutex_t * ) );
172 VLC_EXPORT( int,  __vlc_cond_init,     ( vlc_cond_t * ) );
173 VLC_EXPORT( void,  __vlc_cond_destroy,  ( const char *, int, vlc_cond_t * ) );
174 VLC_EXPORT( int, vlc_threadvar_create, (vlc_threadvar_t * , void (*) (void *) ) );
175 VLC_EXPORT( void, vlc_threadvar_delete, (vlc_threadvar_t *) );
176 VLC_EXPORT( int,  __vlc_thread_create, ( vlc_object_t *, const char *, int, const char *, void * ( * ) ( void * ), int, bool ) );
177 VLC_EXPORT( int,  __vlc_thread_set_priority, ( vlc_object_t *, const char *, int, int ) );
178 VLC_EXPORT( void, __vlc_thread_ready,  ( vlc_object_t * ) );
179 VLC_EXPORT( void, __vlc_thread_join,   ( vlc_object_t *, const char *, int ) );
180
181 /*****************************************************************************
182  * vlc_mutex_lock: lock a mutex
183  *****************************************************************************/
184 #define vlc_mutex_lock( P_MUTEX )                                           \
185     __vlc_mutex_lock( __FILE__, __LINE__, P_MUTEX )
186
187 VLC_EXPORT(void, vlc_pthread_fatal, (const char *action, int error, const char *file, unsigned line));
188
189 #if defined(LIBVLC_USE_PTHREAD)
190 # define VLC_THREAD_ASSERT( action ) \
191     if (val) \
192         vlc_pthread_fatal (action, val, psz_file, i_line)
193 #else
194 # define VLC_THREAD_ASSERT (void)0
195 #endif
196
197 static inline void __vlc_mutex_lock( const char * psz_file, int i_line,
198                                     vlc_mutex_t * p_mutex )
199 {
200 #if defined(LIBVLC_USE_PTHREAD)
201 #   define vlc_assert_locked( m ) \
202            assert (pthread_mutex_lock (m) == EDEADLK)
203     int val = pthread_mutex_lock( p_mutex );
204     VLC_THREAD_ASSERT ("locking mutex");
205
206 #elif defined( UNDER_CE )
207     (void)psz_file; (void)i_line;
208
209     EnterCriticalSection( &p_mutex->csection );
210
211 #elif defined( WIN32 )
212     (void)psz_file; (void)i_line;
213
214     WaitForSingleObject( *p_mutex, INFINITE );
215
216 #elif defined( SYS_BEOS )
217     acquire_sem( p_mutex->lock );
218
219 #endif
220 }
221
222 #ifndef vlc_assert_locked
223 # define vlc_assert_locked( m ) (void)0
224 #endif
225
226 /*****************************************************************************
227  * vlc_mutex_unlock: unlock a mutex
228  *****************************************************************************/
229 #define vlc_mutex_unlock( P_MUTEX )                                         \
230     __vlc_mutex_unlock( __FILE__, __LINE__, P_MUTEX )
231
232 static inline void __vlc_mutex_unlock( const char * psz_file, int i_line,
233                                       vlc_mutex_t *p_mutex )
234 {
235 #if defined(LIBVLC_USE_PTHREAD)
236     int val = pthread_mutex_unlock( p_mutex );
237     VLC_THREAD_ASSERT ("unlocking mutex");
238
239 #elif defined( UNDER_CE )
240     (void)psz_file; (void)i_line;
241
242     LeaveCriticalSection( &p_mutex->csection );
243
244 #elif defined( WIN32 )
245     (void)psz_file; (void)i_line;
246
247     ReleaseMutex( *p_mutex );
248
249 #elif defined( SYS_BEOS )
250     release_sem( p_mutex->lock );
251
252 #endif
253 }
254
255 /*****************************************************************************
256  * vlc_mutex_destroy: destroy a mutex
257  *****************************************************************************/
258 #define vlc_mutex_destroy( P_MUTEX )                                        \
259     __vlc_mutex_destroy( __FILE__, __LINE__, P_MUTEX )
260
261 /*****************************************************************************
262  * vlc_cond_init: initialize a condition
263  *****************************************************************************/
264 #define vlc_cond_init( P_THIS, P_COND )                                     \
265     __vlc_cond_init( P_COND )
266
267 /*****************************************************************************
268  * vlc_cond_signal: start a thread on condition completion
269  *****************************************************************************/
270 #define vlc_cond_signal( P_COND )                                           \
271     __vlc_cond_signal( __FILE__, __LINE__, P_COND )
272
273 static inline void __vlc_cond_signal( const char * psz_file, int i_line,
274                                       vlc_cond_t *p_condvar )
275 {
276 #if defined(LIBVLC_USE_PTHREAD)
277     int val = pthread_cond_signal( p_condvar );
278     VLC_THREAD_ASSERT ("signaling condition variable");
279
280 #elif defined( UNDER_CE ) || defined( WIN32 )
281     (void)psz_file; (void)i_line;
282
283     /* Release one waiting thread if one is available. */
284     /* For this trick to work properly, the vlc_cond_signal must be surrounded
285      * by a mutex. This will prevent another thread from stealing the signal */
286     /* PulseEvent() only works if none of the waiting threads is suspended.
287      * This is particularily problematic under a debug session.
288      * as documented in http://support.microsoft.com/kb/q173260/ */
289     PulseEvent( p_condvar->event );
290
291 #elif defined( SYS_BEOS )
292     while( p_condvar->thread != -1 )
293     {
294         thread_info info;
295         if( get_thread_info(p_condvar->thread, &info) == B_BAD_VALUE )
296             return;
297
298         if( info.state != B_THREAD_SUSPENDED )
299         {
300             /* The  waiting thread is not suspended so it could
301              * have been interrupted beetwen the unlock and the
302              * suspend_thread line. That is why we sleep a little
303              * before retesting p_condver->thread. */
304             snooze( 10000 );
305         }
306         else
307         {
308             /* Ok, we have to wake up that thread */
309             resume_thread( p_condvar->thread );
310         }
311     }
312
313 #endif
314 }
315
316 /*****************************************************************************
317  * vlc_cond_wait: wait until condition completion
318  *****************************************************************************/
319 #define vlc_cond_wait( P_COND, P_MUTEX )                                     \
320     __vlc_cond_wait( __FILE__, __LINE__, P_COND, P_MUTEX  )
321
322 static inline void __vlc_cond_wait( const char * psz_file, int i_line,
323                                     vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex )
324 {
325 #if defined(LIBVLC_USE_PTHREAD)
326     int val = pthread_cond_wait( p_condvar, p_mutex );
327     VLC_THREAD_ASSERT ("waiting on condition");
328
329 #elif defined( UNDER_CE )
330     p_condvar->i_waiting_threads++;
331     LeaveCriticalSection( &p_mutex->csection );
332     WaitForSingleObject( p_condvar->event, INFINITE );
333     p_condvar->i_waiting_threads--;
334
335     /* Reacquire the mutex before returning. */
336     vlc_mutex_lock( p_mutex );
337
338 #elif defined( WIN32 )
339     (void)psz_file; (void)i_line;
340
341     /* Increase our wait count */
342     p_condvar->i_waiting_threads++;
343     SignalObjectAndWait( *p_mutex, p_condvar->event, INFINITE, FALSE );
344     p_condvar->i_waiting_threads--;
345
346     /* Reacquire the mutex before returning. */
347     vlc_mutex_lock( p_mutex );
348
349 #elif defined( SYS_BEOS )
350     /* The p_condvar->thread var is initialized before the unlock because
351      * it enables to identify when the thread is interrupted beetwen the
352      * unlock line and the suspend_thread line */
353     p_condvar->thread = find_thread( NULL );
354     vlc_mutex_unlock( p_mutex );
355     suspend_thread( p_condvar->thread );
356     p_condvar->thread = -1;
357
358     vlc_mutex_lock( p_mutex );
359
360 #endif
361 }
362
363
364 /*****************************************************************************
365  * vlc_cond_timedwait: wait until condition completion or expiration
366  *****************************************************************************
367  * Returns 0 if object signaled, an error code in case of timeout or error.
368  *****************************************************************************/
369 #define vlc_cond_timedwait( P_COND, P_MUTEX, DEADLINE )                      \
370     __vlc_cond_timedwait( __FILE__, __LINE__, P_COND, P_MUTEX, DEADLINE  )
371
372 static inline int __vlc_cond_timedwait( const char * psz_file, int i_line,
373                                         vlc_cond_t *p_condvar,
374                                         vlc_mutex_t *p_mutex,
375                                         mtime_t deadline )
376 {
377 #if defined(LIBVLC_USE_PTHREAD)
378     lldiv_t d = lldiv( deadline, 1000000 );
379     struct timespec ts = { d.quot, d.rem * 1000 };
380
381     int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
382     if (val == ETIMEDOUT)
383         return ETIMEDOUT; /* this error is perfectly normal */
384     VLC_THREAD_ASSERT ("timed-waiting on condition");
385
386 #elif defined( UNDER_CE )
387     mtime_t delay_ms = (deadline - mdate())/1000;
388     DWORD result;
389     if( delay_ms < 0 )
390         delay_ms = 0;
391
392     p_condvar->i_waiting_threads++;
393     LeaveCriticalSection( &p_mutex->csection );
394     result = WaitForSingleObject( p_condvar->event, delay_ms );
395     p_condvar->i_waiting_threads--;
396
397     /* Reacquire the mutex before returning. */
398     vlc_mutex_lock( p_mutex );
399
400     if(result == WAIT_TIMEOUT)
401        return ETIMEDOUT; /* this error is perfectly normal */
402
403     (void)psz_file; (void)i_line;
404
405 #elif defined( WIN32 )
406     mtime_t delay_ms = (deadline - mdate())/1000;
407     DWORD result;
408     if( delay_ms < 0 )
409         delay_ms = 0;
410
411     /* Increase our wait count */
412     p_condvar->i_waiting_threads++;
413     result = SignalObjectAndWait( *p_mutex, p_condvar->event,
414                                   delay_ms, FALSE );
415     p_condvar->i_waiting_threads--;
416
417     /* Reacquire the mutex before returning. */
418     vlc_mutex_lock( p_mutex );
419     if(result == WAIT_TIMEOUT)
420        return ETIMEDOUT; /* this error is perfectly normal */
421
422     (void)psz_file; (void)i_line;
423
424 #elif defined( SYS_BEOS )
425 #   error Unimplemented
426
427 #endif
428
429     return 0;
430 }
431
432 /*****************************************************************************
433  * vlc_cond_destroy: destroy a condition
434  *****************************************************************************/
435 #define vlc_cond_destroy( P_COND )                                          \
436     __vlc_cond_destroy( __FILE__, __LINE__, P_COND )
437
438 /*****************************************************************************
439  * vlc_threadvar_set: create: set the value of a thread-local variable
440  *****************************************************************************/
441 static inline int vlc_threadvar_set( vlc_threadvar_t * p_tls, void *p_value )
442 {
443     int i_ret;
444
445 #if defined(LIBVLC_USE_PTHREAD)
446     i_ret = pthread_setspecific( *p_tls, p_value );
447
448 #elif defined( SYS_BEOS )
449     i_ret = EINVAL;
450
451 #elif defined( UNDER_CE ) || defined( WIN32 )
452     i_ret = TlsSetValue( *p_tls, p_value ) ? EINVAL : 0;
453
454 #endif
455
456     return i_ret;
457 }
458
459 /*****************************************************************************
460  * vlc_threadvar_get: create: get the value of a thread-local variable
461  *****************************************************************************/
462 static inline void* vlc_threadvar_get( vlc_threadvar_t * p_tls )
463 {
464     void *p_ret;
465
466 #if defined(LIBVLC_USE_PTHREAD)
467     p_ret = pthread_getspecific( *p_tls );
468
469 #elif defined( SYS_BEOS )
470     p_ret = NULL;
471
472 #elif defined( UNDER_CE ) || defined( WIN32 )
473     p_ret = TlsGetValue( *p_tls );
474
475 #endif
476
477     return p_ret;
478 }
479
480 # if defined (_POSIX_SPIN_LOCKS) && ((_POSIX_SPIN_LOCKS - 0) > 0)
481 typedef pthread_spinlock_t vlc_spinlock_t;
482
483 /**
484  * Initializes a spinlock.
485  */
486 static inline int vlc_spin_init (vlc_spinlock_t *spin)
487 {
488     return pthread_spin_init (spin, PTHREAD_PROCESS_PRIVATE);
489 }
490
491 /**
492  * Acquires a spinlock.
493  */
494 static inline void vlc_spin_lock (vlc_spinlock_t *spin)
495 {
496     pthread_spin_lock (spin);
497 }
498
499 /**
500  * Releases a spinlock.
501  */
502 static inline void vlc_spin_unlock (vlc_spinlock_t *spin)
503 {
504     pthread_spin_unlock (spin);
505 }
506
507 /**
508  * Deinitializes a spinlock.
509  */
510 static inline void vlc_spin_destroy (vlc_spinlock_t *spin)
511 {
512     pthread_spin_destroy (spin);
513 }
514
515 #elif defined( WIN32 )
516
517 typedef CRITICAL_SECTION vlc_spinlock_t;
518
519 /**
520  * Initializes a spinlock.
521  */
522 static inline int vlc_spin_init (vlc_spinlock_t *spin)
523 {
524     return !InitializeCriticalSectionAndSpinCount(spin, 4000);
525 }
526
527 /**
528  * Acquires a spinlock.
529  */
530 static inline void vlc_spin_lock (vlc_spinlock_t *spin)
531 {
532     EnterCriticalSection(spin);
533 }
534
535 /**
536  * Releases a spinlock.
537  */
538 static inline void vlc_spin_unlock (vlc_spinlock_t *spin)
539 {
540     LeaveCriticalSection(spin);
541 }
542
543 /**
544  * Deinitializes a spinlock.
545  */
546 static inline void vlc_spin_destroy (vlc_spinlock_t *spin)
547 {
548     DeleteCriticalSection(spin);
549 }
550
551 #else
552
553 /* Fallback to plain mutexes if spinlocks are not available */
554 typedef vlc_mutex_t vlc_spinlock_t;
555
556 static inline int vlc_spin_init (vlc_spinlock_t *spin)
557 {
558     return vlc_mutex_init (spin);
559 }
560
561 # define vlc_spin_lock    vlc_mutex_lock
562 # define vlc_spin_unlock  vlc_mutex_unlock
563 # define vlc_spin_destroy vlc_mutex_destroy
564 #endif
565
566 /*****************************************************************************
567  * vlc_thread_create: create a thread
568  *****************************************************************************/
569 #define vlc_thread_create( P_THIS, PSZ_NAME, FUNC, PRIORITY, WAIT )         \
570     __vlc_thread_create( VLC_OBJECT(P_THIS), __FILE__, __LINE__, PSZ_NAME, (void * ( * ) ( void * ))FUNC, PRIORITY, WAIT )
571
572 /*****************************************************************************
573  * vlc_thread_set_priority: set the priority of the calling thread
574  *****************************************************************************/
575 #define vlc_thread_set_priority( P_THIS, PRIORITY )                         \
576     __vlc_thread_set_priority( VLC_OBJECT(P_THIS), __FILE__, __LINE__, PRIORITY )
577
578 /*****************************************************************************
579  * vlc_thread_ready: tell the parent thread we were successfully spawned
580  *****************************************************************************/
581 #define vlc_thread_ready( P_THIS )                                          \
582     __vlc_thread_ready( VLC_OBJECT(P_THIS) )
583
584 /*****************************************************************************
585  * vlc_thread_join: wait until a thread exits
586  *****************************************************************************/
587 #define vlc_thread_join( P_THIS )                                           \
588     __vlc_thread_join( VLC_OBJECT(P_THIS), __FILE__, __LINE__ )
589
590 #endif /* !_VLC_THREADS_H */