]> git.sesse.net Git - vlc/blob - include/vlc_threads.h
Win32 condition variable: remove write-only counter
[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 delay_ms = (deadline - mdate())/1000;
390     DWORD result;
391     if( delay_ms < 0 )
392         delay_ms = 0;
393
394     /* Increase our wait count */
395     result = SignalObjectAndWait( *p_mutex, *p_condvar,
396                                   delay_ms, FALSE );
397
398     /* Reacquire the mutex before returning. */
399     vlc_mutex_lock( p_mutex );
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( SYS_BEOS )
406 #   error Unimplemented
407
408 #endif
409
410     return 0;
411 }
412
413 /*****************************************************************************
414  * vlc_cond_destroy: destroy a condition
415  *****************************************************************************/
416 #define vlc_cond_destroy( P_COND )                                          \
417     __vlc_cond_destroy( __FILE__, __LINE__, P_COND )
418
419 /*****************************************************************************
420  * vlc_threadvar_set: create: set the value of a thread-local variable
421  *****************************************************************************/
422 static inline int vlc_threadvar_set( vlc_threadvar_t * p_tls, void *p_value )
423 {
424     int i_ret;
425
426 #if defined(LIBVLC_USE_PTHREAD)
427     i_ret = pthread_setspecific( *p_tls, p_value );
428
429 #elif defined( SYS_BEOS )
430     i_ret = EINVAL;
431
432 #elif defined( UNDER_CE ) || defined( WIN32 )
433     i_ret = TlsSetValue( *p_tls, p_value ) ? EINVAL : 0;
434
435 #endif
436
437     return i_ret;
438 }
439
440 /*****************************************************************************
441  * vlc_threadvar_get: create: get the value of a thread-local variable
442  *****************************************************************************/
443 static inline void* vlc_threadvar_get( vlc_threadvar_t * p_tls )
444 {
445     void *p_ret;
446
447 #if defined(LIBVLC_USE_PTHREAD)
448     p_ret = pthread_getspecific( *p_tls );
449
450 #elif defined( SYS_BEOS )
451     p_ret = NULL;
452
453 #elif defined( UNDER_CE ) || defined( WIN32 )
454     p_ret = TlsGetValue( *p_tls );
455
456 #endif
457
458     return p_ret;
459 }
460
461 # if defined (_POSIX_SPIN_LOCKS) && ((_POSIX_SPIN_LOCKS - 0) > 0)
462 typedef pthread_spinlock_t vlc_spinlock_t;
463
464 /**
465  * Initializes a spinlock.
466  */
467 static inline int vlc_spin_init (vlc_spinlock_t *spin)
468 {
469     return pthread_spin_init (spin, PTHREAD_PROCESS_PRIVATE);
470 }
471
472 /**
473  * Acquires a spinlock.
474  */
475 static inline void vlc_spin_lock (vlc_spinlock_t *spin)
476 {
477     pthread_spin_lock (spin);
478 }
479
480 /**
481  * Releases a spinlock.
482  */
483 static inline void vlc_spin_unlock (vlc_spinlock_t *spin)
484 {
485     pthread_spin_unlock (spin);
486 }
487
488 /**
489  * Deinitializes a spinlock.
490  */
491 static inline void vlc_spin_destroy (vlc_spinlock_t *spin)
492 {
493     pthread_spin_destroy (spin);
494 }
495
496 #elif defined( WIN32 )
497
498 typedef CRITICAL_SECTION vlc_spinlock_t;
499
500 /**
501  * Initializes a spinlock.
502  */
503 static inline int vlc_spin_init (vlc_spinlock_t *spin)
504 {
505     return !InitializeCriticalSectionAndSpinCount(spin, 4000);
506 }
507
508 /**
509  * Acquires a spinlock.
510  */
511 static inline void vlc_spin_lock (vlc_spinlock_t *spin)
512 {
513     EnterCriticalSection(spin);
514 }
515
516 /**
517  * Releases a spinlock.
518  */
519 static inline void vlc_spin_unlock (vlc_spinlock_t *spin)
520 {
521     LeaveCriticalSection(spin);
522 }
523
524 /**
525  * Deinitializes a spinlock.
526  */
527 static inline void vlc_spin_destroy (vlc_spinlock_t *spin)
528 {
529     DeleteCriticalSection(spin);
530 }
531
532 #else
533
534 /* Fallback to plain mutexes if spinlocks are not available */
535 typedef vlc_mutex_t vlc_spinlock_t;
536
537 static inline int vlc_spin_init (vlc_spinlock_t *spin)
538 {
539     return vlc_mutex_init (spin);
540 }
541
542 # define vlc_spin_lock    vlc_mutex_lock
543 # define vlc_spin_unlock  vlc_mutex_unlock
544 # define vlc_spin_destroy vlc_mutex_destroy
545 #endif
546
547 /**
548  * Issues a full memory barrier.
549  */
550 #if defined (__APPLE__)
551 # include <libkern/OSAtomic.h> /* OSMemoryBarrier() */
552 #endif
553 static inline void barrier (void)
554 {
555 #if defined (__GNUC__) && (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)
556     __sync_synchronize ();
557 #elif defined(__APPLE__)
558     OSMemoryBarrier ();
559 #elif defined(__powerpc__)
560     asm volatile ("sync":::"memory");
561 #elif defined(__i386__)
562     asm volatile ("mfence":::"memory");
563 #elif defined (LIBVLC_USE_PTHREAD)
564     static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
565     pthread_mutex_lock (&lock);
566     pthread_mutex_unlock (&lock);
567 #else
568 # error barrier not implemented!
569 #endif
570 }
571
572 /*****************************************************************************
573  * vlc_thread_create: create a thread
574  *****************************************************************************/
575 #define vlc_thread_create( P_THIS, PSZ_NAME, FUNC, PRIORITY, WAIT )         \
576     __vlc_thread_create( VLC_OBJECT(P_THIS), __FILE__, __LINE__, PSZ_NAME, FUNC, PRIORITY, WAIT )
577
578 /*****************************************************************************
579  * vlc_thread_set_priority: set the priority of the calling thread
580  *****************************************************************************/
581 #define vlc_thread_set_priority( P_THIS, PRIORITY )                         \
582     __vlc_thread_set_priority( VLC_OBJECT(P_THIS), __FILE__, __LINE__, PRIORITY )
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 */