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