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