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 * Copyright © 2007-2008 Rémi Denis-Courmont
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>
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.
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.
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 *****************************************************************************/
28 #ifndef VLC_THREADS_H_
29 #define VLC_THREADS_H_
33 * This file defines structures and functions for handling threads in vlc
37 #if defined( UNDER_CE )
39 #elif defined( WIN32 )
40 # include <process.h> /* Win32 API */
43 #else /* pthreads (like Linux & BSD) */
44 # define LIBVLC_USE_PTHREAD 1
45 # define LIBVLC_USE_PTHREAD_CANCEL 1
46 # define _APPLE_C_SOURCE 1 /* Proper pthread semantics on OSX */
48 # include <stdlib.h> /* lldiv_t definition (only in C99) */
49 # include <unistd.h> /* _POSIX_SPIN_LOCKS */
51 /* Needed for pthread_cond_timedwait */
57 /*****************************************************************************
59 *****************************************************************************/
61 /* Thread priorities */
63 # define VLC_THREAD_PRIORITY_LOW 0
64 # define VLC_THREAD_PRIORITY_INPUT 22
65 # define VLC_THREAD_PRIORITY_AUDIO 22
66 # define VLC_THREAD_PRIORITY_VIDEO 0
67 # define VLC_THREAD_PRIORITY_OUTPUT 22
68 # define VLC_THREAD_PRIORITY_HIGHEST 22
70 #elif defined(LIBVLC_USE_PTHREAD)
71 # define VLC_THREAD_PRIORITY_LOW 0
72 # define VLC_THREAD_PRIORITY_INPUT 10
73 # define VLC_THREAD_PRIORITY_AUDIO 5
74 # define VLC_THREAD_PRIORITY_VIDEO 0
75 # define VLC_THREAD_PRIORITY_OUTPUT 15
76 # define VLC_THREAD_PRIORITY_HIGHEST 20
78 #elif defined(WIN32) || defined(UNDER_CE)
79 /* Define different priorities for WinNT/2K/XP and Win9x/Me */
80 # define VLC_THREAD_PRIORITY_LOW 0
81 # define VLC_THREAD_PRIORITY_INPUT \
82 (IS_WINNT ? THREAD_PRIORITY_ABOVE_NORMAL : 0)
83 # define VLC_THREAD_PRIORITY_AUDIO \
84 (IS_WINNT ? THREAD_PRIORITY_HIGHEST : 0)
85 # define VLC_THREAD_PRIORITY_VIDEO \
86 (IS_WINNT ? 0 : THREAD_PRIORITY_BELOW_NORMAL )
87 # define VLC_THREAD_PRIORITY_OUTPUT \
88 (IS_WINNT ? THREAD_PRIORITY_ABOVE_NORMAL : 0)
89 # define VLC_THREAD_PRIORITY_HIGHEST \
90 (IS_WINNT ? THREAD_PRIORITY_TIME_CRITICAL : 0)
93 # define VLC_THREAD_PRIORITY_LOW 0
94 # define VLC_THREAD_PRIORITY_INPUT 0
95 # define VLC_THREAD_PRIORITY_AUDIO 0
96 # define VLC_THREAD_PRIORITY_VIDEO 0
97 # define VLC_THREAD_PRIORITY_OUTPUT 0
98 # define VLC_THREAD_PRIORITY_HIGHEST 0
102 /*****************************************************************************
104 *****************************************************************************/
106 #if defined (LIBVLC_USE_PTHREAD)
107 typedef pthread_t vlc_thread_t;
108 typedef pthread_mutex_t vlc_mutex_t;
109 typedef pthread_cond_t vlc_cond_t;
110 typedef pthread_key_t vlc_threadvar_t;
112 #elif defined( WIN32 ) || defined( UNDER_CE )
116 void *(*entry) (void *);
120 typedef HANDLE vlc_mutex_t;
121 typedef HANDLE vlc_cond_t;
122 typedef DWORD vlc_threadvar_t;
126 #if defined( WIN32 ) && !defined ETIMEDOUT
127 # define ETIMEDOUT 10060 /* This is the value in winsock.h. */
130 /*****************************************************************************
131 * Function definitions
132 *****************************************************************************/
133 VLC_EXPORT( int, vlc_mutex_init, ( vlc_mutex_t * ) );
134 VLC_EXPORT( int, vlc_mutex_init_recursive, ( vlc_mutex_t * ) );
135 VLC_EXPORT( void, __vlc_mutex_destroy, ( const char *, int, vlc_mutex_t * ) );
136 VLC_EXPORT( int, vlc_cond_init, ( vlc_cond_t * ) );
137 VLC_EXPORT( void, __vlc_cond_destroy, ( const char *, int, vlc_cond_t * ) );
138 VLC_EXPORT( void, vlc_cond_broadcast, (vlc_cond_t *) );
139 VLC_EXPORT( int, vlc_threadvar_create, (vlc_threadvar_t * , void (*) (void *) ) );
140 VLC_EXPORT( void, vlc_threadvar_delete, (vlc_threadvar_t *) );
141 VLC_EXPORT( int, __vlc_thread_create, ( vlc_object_t *, const char *, int, const char *, void * ( * ) ( vlc_object_t * ), int, bool ) );
142 VLC_EXPORT( int, __vlc_thread_set_priority, ( vlc_object_t *, const char *, int, int ) );
143 VLC_EXPORT( void, __vlc_thread_join, ( vlc_object_t * ) );
145 VLC_EXPORT( int, vlc_clone, (vlc_thread_t *, void * (*) (void *), void *, int) );
146 VLC_EXPORT( void, vlc_cancel, (vlc_thread_t) );
147 VLC_EXPORT( void, vlc_join, (vlc_thread_t, void **) );
148 VLC_EXPORT (void, vlc_control_cancel, (int cmd, ...));
150 #ifndef LIBVLC_USE_PTHREAD_CANCEL
161 #define vlc_thread_ready vlc_object_signal
163 /*****************************************************************************
164 * vlc_mutex_lock: lock a mutex
165 *****************************************************************************/
166 #define vlc_mutex_lock( P_MUTEX ) \
167 __vlc_mutex_lock( __FILE__, __LINE__, P_MUTEX )
169 VLC_EXPORT(void, vlc_thread_fatal, (const char *action, int error, const char *function, const char *file, unsigned line));
171 #if defined(LIBVLC_USE_PTHREAD)
172 # define VLC_THREAD_ASSERT( action ) \
174 vlc_thread_fatal (action, val, __func__, psz_file, i_line)
176 # define VLC_THREAD_ASSERT ((void)(val))
179 static inline void __vlc_mutex_lock( const char * psz_file, int i_line,
180 vlc_mutex_t * p_mutex )
182 #if defined(LIBVLC_USE_PTHREAD)
183 # define vlc_assert_locked( m ) \
184 assert (pthread_mutex_lock (m) == EDEADLK)
185 int val = pthread_mutex_lock( p_mutex );
186 VLC_THREAD_ASSERT ("locking mutex");
188 #elif defined( UNDER_CE )
189 (void)psz_file; (void)i_line;
191 EnterCriticalSection( &p_mutex->csection );
193 #elif defined( WIN32 )
194 (void)psz_file; (void)i_line;
196 WaitForSingleObject( *p_mutex, INFINITE );
201 #ifndef vlc_assert_locked
202 # define vlc_assert_locked( m ) (void)m
205 /*****************************************************************************
206 * vlc_mutex_unlock: unlock a mutex
207 *****************************************************************************/
208 #define vlc_mutex_unlock( P_MUTEX ) \
209 __vlc_mutex_unlock( __FILE__, __LINE__, P_MUTEX )
211 static inline void __vlc_mutex_unlock( const char * psz_file, int i_line,
212 vlc_mutex_t *p_mutex )
214 #if defined(LIBVLC_USE_PTHREAD)
215 int val = pthread_mutex_unlock( p_mutex );
216 VLC_THREAD_ASSERT ("unlocking mutex");
218 #elif defined( UNDER_CE )
219 (void)psz_file; (void)i_line;
221 LeaveCriticalSection( &p_mutex->csection );
223 #elif defined( WIN32 )
224 (void)psz_file; (void)i_line;
226 ReleaseMutex( *p_mutex );
231 /*****************************************************************************
232 * vlc_mutex_destroy: destroy a mutex
233 *****************************************************************************/
234 #define vlc_mutex_destroy( P_MUTEX ) \
235 __vlc_mutex_destroy( __FILE__, __LINE__, P_MUTEX )
238 * Save the cancellation state and disable cancellation for the calling thread.
239 * This function must be called before entering a piece of code that is not
241 * @return Previous cancellation state (opaque value).
243 static inline int vlc_savecancel (void)
246 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
247 (void) pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
249 vlc_control_cancel (VLC_SAVE_CANCEL, &state);
255 * Restore the cancellation state for the calling thread.
256 * @param state previous state as returned by vlc_savecancel().
257 * @return Nothing, always succeeds.
259 static inline void vlc_restorecancel (int state)
261 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
262 (void) pthread_setcancelstate (state, NULL);
264 vlc_control_cancel (VLC_RESTORE_CANCEL, state);
269 * Issues an explicit deferred cancellation point.
270 * This has no effect if thread cancellation is disabled.
271 * This can be called when there is a rather slow non-sleeping operation.
273 static inline void vlc_testcancel (void)
275 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
276 pthread_testcancel ();
278 vlc_control_cancel (VLC_TEST_CANCEL);
282 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
284 * Registers a new procedure to run if the thread is cancelled (or otherwise
285 * exits prematurely). Any call to vlc_cleanup_push() <b>must</b> paired with a
286 * call to either vlc_cleanup_pop() or vlc_cleanup_run(). Branching into or out
287 * of the block between these two function calls is not allowed (read: it will
288 * likely crash the whole process). If multiple procedures are registered,
289 * they are handled in last-in first-out order.
291 * @param routine procedure to call if the thread ends
292 * @param arg argument for the procedure
294 # define vlc_cleanup_push( routine, arg ) pthread_cleanup_push (routine, arg)
297 * Removes a cleanup procedure that was previously registered with
298 * vlc_cleanup_push().
300 # define vlc_cleanup_pop( ) pthread_cleanup_pop (0)
303 * Removes a cleanup procedure that was previously registered with
304 * vlc_cleanup_push(), and executes it.
306 # define vlc_cleanup_run( ) pthread_cleanup_pop (1)
308 typedef struct vlc_cleanup_t vlc_cleanup_t;
313 void (*proc) (void *);
317 /* This macros opens a code block on purpose. This is needed for multiple
318 * calls within a single function. This also prevent Win32 developpers from
319 * writing code that would break on POSIX (POSIX opens a block as well). */
320 # define vlc_cleanup_push( routine, arg ) \
322 vlc_cleanup_t vlc_cleanup_data = { NULL, routine, arg, }; \
323 vlc_control_cancel (VLC_CLEANUP_PUSH, &vlc_cleanup_data)
325 # define vlc_cleanup_pop( ) \
326 vlc_control_cancel (VLC_CLEANUP_POP); \
329 # define vlc_cleanup_run( ) \
330 vlc_control_cancel (VLC_CLEANUP_POP); \
331 vlc_cleanup_data.proc (vlc_cleanup_data.data); \
334 #endif /* LIBVLC_USE_PTHREAD_CANCEL */
336 static inline void vlc_cleanup_lock (void *lock)
338 vlc_mutex_unlock ((vlc_mutex_t *)lock);
340 #define mutex_cleanup_push( lock ) vlc_cleanup_push (vlc_cleanup_lock, lock)
342 /*****************************************************************************
343 * vlc_cond_signal: start a thread on condition completion
344 *****************************************************************************/
345 #define vlc_cond_signal( P_COND ) \
346 __vlc_cond_signal( __FILE__, __LINE__, P_COND )
348 static inline void __vlc_cond_signal( const char * psz_file, int i_line,
349 vlc_cond_t *p_condvar )
351 #if defined(LIBVLC_USE_PTHREAD)
352 int val = pthread_cond_signal( p_condvar );
353 VLC_THREAD_ASSERT ("signaling condition variable");
355 #elif defined( UNDER_CE ) || defined( WIN32 )
356 (void)psz_file; (void)i_line;
358 /* Release one waiting thread if one is available. */
359 /* For this trick to work properly, the vlc_cond_signal must be surrounded
360 * by a mutex. This will prevent another thread from stealing the signal */
361 /* PulseEvent() only works if none of the waiting threads is suspended.
362 * This is particularily problematic under a debug session.
363 * as documented in http://support.microsoft.com/kb/q173260/ */
364 PulseEvent( *p_condvar );
369 /*****************************************************************************
370 * vlc_cond_wait: wait until condition completion
371 *****************************************************************************/
372 #define vlc_cond_wait( P_COND, P_MUTEX ) \
373 __vlc_cond_wait( __FILE__, __LINE__, P_COND, P_MUTEX )
375 static inline void __vlc_cond_wait( const char * psz_file, int i_line,
376 vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex )
378 #if defined(LIBVLC_USE_PTHREAD)
379 int val = pthread_cond_wait( p_condvar, p_mutex );
380 VLC_THREAD_ASSERT ("waiting on condition");
382 #elif defined( UNDER_CE )
383 LeaveCriticalSection( &p_mutex->csection );
384 WaitForSingleObject( *p_condvar, INFINITE );
386 /* Reacquire the mutex before returning. */
387 vlc_mutex_lock( p_mutex );
389 #elif defined( WIN32 )
392 while (SignalObjectAndWait (*p_mutex, *p_condvar, INFINITE, TRUE)
393 == WAIT_IO_COMPLETION);
395 /* Reacquire the mutex before returning. */
396 vlc_mutex_lock( p_mutex );
398 (void)psz_file; (void)i_line;
404 /*****************************************************************************
405 * vlc_cond_timedwait: wait until condition completion or expiration
406 *****************************************************************************
407 * Returns 0 if object signaled, an error code in case of timeout or error.
408 *****************************************************************************/
409 #define vlc_cond_timedwait( c, m, d ) \
410 __vlc_cond_timedwait( __FILE__, __LINE__, c, m, check_deadline(d) )
412 static inline int __vlc_cond_timedwait( const char * psz_file, int i_line,
413 vlc_cond_t *p_condvar,
414 vlc_mutex_t *p_mutex,
417 #if defined(LIBVLC_USE_PTHREAD)
418 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
419 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
421 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
422 if (val != ETIMEDOUT)
423 VLC_THREAD_ASSERT ("timed-waiting on condition");
426 #elif defined( UNDER_CE )
427 mtime_t delay_ms = (deadline - mdate()) / (CLOCK_FREQ / 1000);
432 LeaveCriticalSection( &p_mutex->csection );
433 result = WaitForSingleObject( *p_condvar, delay_ms );
435 /* Reacquire the mutex before returning. */
436 vlc_mutex_lock( p_mutex );
438 (void)psz_file; (void)i_line;
440 return (result == WAIT_TIMEOUT) ? ETIMEDOUT : 0;
442 #elif defined( WIN32 )
445 (void)psz_file; (void)i_line;
451 mtime_t total = (deadline - mdate ())/1000;
455 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
456 result = SignalObjectAndWait (*p_mutex, *p_condvar, delay, TRUE);
458 while (result == WAIT_IO_COMPLETION);
460 /* Reacquire the mutex before return/cancel. */
461 vlc_mutex_lock (p_mutex);
462 return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
467 /*****************************************************************************
468 * vlc_cond_destroy: destroy a condition
469 *****************************************************************************/
470 #define vlc_cond_destroy( P_COND ) \
471 __vlc_cond_destroy( __FILE__, __LINE__, P_COND )
473 /*****************************************************************************
474 * vlc_threadvar_set: create: set the value of a thread-local variable
475 *****************************************************************************/
476 static inline int vlc_threadvar_set( vlc_threadvar_t * p_tls, void *p_value )
480 #if defined(LIBVLC_USE_PTHREAD)
481 i_ret = pthread_setspecific( *p_tls, p_value );
483 #elif defined( UNDER_CE ) || defined( WIN32 )
484 i_ret = TlsSetValue( *p_tls, p_value ) ? EINVAL : 0;
491 /*****************************************************************************
492 * vlc_threadvar_get: create: get the value of a thread-local variable
493 *****************************************************************************/
494 static inline void* vlc_threadvar_get( vlc_threadvar_t * p_tls )
498 #if defined(LIBVLC_USE_PTHREAD)
499 p_ret = pthread_getspecific( *p_tls );
501 #elif defined( UNDER_CE ) || defined( WIN32 )
502 p_ret = TlsGetValue( *p_tls );
509 # if defined (_POSIX_SPIN_LOCKS) && ((_POSIX_SPIN_LOCKS - 0) > 0)
510 typedef pthread_spinlock_t vlc_spinlock_t;
513 * Initializes a spinlock.
515 static inline int vlc_spin_init (vlc_spinlock_t *spin)
517 return pthread_spin_init (spin, PTHREAD_PROCESS_PRIVATE);
521 * Acquires a spinlock.
523 static inline void vlc_spin_lock (vlc_spinlock_t *spin)
525 pthread_spin_lock (spin);
529 * Releases a spinlock.
531 static inline void vlc_spin_unlock (vlc_spinlock_t *spin)
533 pthread_spin_unlock (spin);
537 * Deinitializes a spinlock.
539 static inline void vlc_spin_destroy (vlc_spinlock_t *spin)
541 pthread_spin_destroy (spin);
544 #elif defined( WIN32 )
546 typedef CRITICAL_SECTION vlc_spinlock_t;
549 * Initializes a spinlock.
551 static inline int vlc_spin_init (vlc_spinlock_t *spin)
553 return !InitializeCriticalSectionAndSpinCount(spin, 4000);
557 * Acquires a spinlock.
559 static inline void vlc_spin_lock (vlc_spinlock_t *spin)
561 EnterCriticalSection(spin);
565 * Releases a spinlock.
567 static inline void vlc_spin_unlock (vlc_spinlock_t *spin)
569 LeaveCriticalSection(spin);
573 * Deinitializes a spinlock.
575 static inline void vlc_spin_destroy (vlc_spinlock_t *spin)
577 DeleteCriticalSection(spin);
582 /* Fallback to plain mutexes if spinlocks are not available */
583 typedef vlc_mutex_t vlc_spinlock_t;
585 static inline int vlc_spin_init (vlc_spinlock_t *spin)
587 return vlc_mutex_init (spin);
590 # define vlc_spin_lock vlc_mutex_lock
591 # define vlc_spin_unlock vlc_mutex_unlock
592 # define vlc_spin_destroy vlc_mutex_destroy
596 * Issues a full memory barrier.
598 #if defined (__APPLE__)
599 # include <libkern/OSAtomic.h> /* OSMemoryBarrier() */
601 static inline void barrier (void)
603 #if defined (__GNUC__) && (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)
604 __sync_synchronize ();
605 #elif defined(__APPLE__)
607 #elif defined(__powerpc__)
608 asm volatile ("sync":::"memory");
609 #elif defined(__i386__)
610 asm volatile ("mfence":::"memory");
613 vlc_spin_init (&spin);
614 vlc_spin_lock (&spin);
615 vlc_spin_unlock (&spin);
616 vlc_spin_destroy (&spin);
620 /*****************************************************************************
621 * vlc_thread_create: create a thread
622 *****************************************************************************/
623 #define vlc_thread_create( P_THIS, PSZ_NAME, FUNC, PRIORITY, WAIT ) \
624 __vlc_thread_create( VLC_OBJECT(P_THIS), __FILE__, __LINE__, PSZ_NAME, FUNC, PRIORITY, WAIT )
626 /*****************************************************************************
627 * vlc_thread_set_priority: set the priority of the calling thread
628 *****************************************************************************/
629 #define vlc_thread_set_priority( P_THIS, PRIORITY ) \
630 __vlc_thread_set_priority( VLC_OBJECT(P_THIS), __FILE__, __LINE__, PRIORITY )
632 /*****************************************************************************
633 * vlc_thread_join: wait until a thread exits
634 *****************************************************************************/
635 #define vlc_thread_join( P_THIS ) \
636 __vlc_thread_join( VLC_OBJECT(P_THIS) )
638 #endif /* !_VLC_THREADS_H */