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