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 #elif defined( SYS_BEOS ) /* BeOS */
44 # include <kernel/OS.h>
45 # include <kernel/scheduler.h>
46 # include <byteorder.h>
48 #else /* pthreads (like Linux & BSD) */
49 # define LIBVLC_USE_PTHREAD 1
50 # define LIBVLC_USE_PTHREAD_CANCEL 1
51 # define _APPLE_C_SOURCE 1 /* Proper pthread semantics on OSX */
53 # include <stdlib.h> /* lldiv_t definition (only in C99) */
54 # include <unistd.h> /* _POSIX_SPIN_LOCKS */
56 /* Needed for pthread_cond_timedwait */
62 /*****************************************************************************
64 *****************************************************************************/
66 /* Thread priorities */
68 # define VLC_THREAD_PRIORITY_LOW 0
69 # define VLC_THREAD_PRIORITY_INPUT 22
70 # define VLC_THREAD_PRIORITY_AUDIO 22
71 # define VLC_THREAD_PRIORITY_VIDEO 0
72 # define VLC_THREAD_PRIORITY_OUTPUT 22
73 # define VLC_THREAD_PRIORITY_HIGHEST 22
75 #elif defined(SYS_BEOS)
76 # define VLC_THREAD_PRIORITY_LOW 5
77 # define VLC_THREAD_PRIORITY_INPUT 10
78 # define VLC_THREAD_PRIORITY_AUDIO 10
79 # define VLC_THREAD_PRIORITY_VIDEO 5
80 # define VLC_THREAD_PRIORITY_OUTPUT 15
81 # define VLC_THREAD_PRIORITY_HIGHEST 15
83 #elif defined(LIBVLC_USE_PTHREAD)
84 # define VLC_THREAD_PRIORITY_LOW 0
85 # define VLC_THREAD_PRIORITY_INPUT 10
86 # define VLC_THREAD_PRIORITY_AUDIO 5
87 # define VLC_THREAD_PRIORITY_VIDEO 0
88 # define VLC_THREAD_PRIORITY_OUTPUT 15
89 # define VLC_THREAD_PRIORITY_HIGHEST 20
91 #elif defined(WIN32) || defined(UNDER_CE)
92 /* Define different priorities for WinNT/2K/XP and Win9x/Me */
93 # define VLC_THREAD_PRIORITY_LOW 0
94 # define VLC_THREAD_PRIORITY_INPUT \
95 (IS_WINNT ? THREAD_PRIORITY_ABOVE_NORMAL : 0)
96 # define VLC_THREAD_PRIORITY_AUDIO \
97 (IS_WINNT ? THREAD_PRIORITY_HIGHEST : 0)
98 # define VLC_THREAD_PRIORITY_VIDEO \
99 (IS_WINNT ? 0 : THREAD_PRIORITY_BELOW_NORMAL )
100 # define VLC_THREAD_PRIORITY_OUTPUT \
101 (IS_WINNT ? THREAD_PRIORITY_ABOVE_NORMAL : 0)
102 # define VLC_THREAD_PRIORITY_HIGHEST \
103 (IS_WINNT ? THREAD_PRIORITY_TIME_CRITICAL : 0)
106 # define VLC_THREAD_PRIORITY_LOW 0
107 # define VLC_THREAD_PRIORITY_INPUT 0
108 # define VLC_THREAD_PRIORITY_AUDIO 0
109 # define VLC_THREAD_PRIORITY_VIDEO 0
110 # define VLC_THREAD_PRIORITY_OUTPUT 0
111 # define VLC_THREAD_PRIORITY_HIGHEST 0
115 /*****************************************************************************
117 *****************************************************************************/
119 #if defined (LIBVLC_USE_PTHREAD)
120 typedef pthread_t vlc_thread_t;
121 typedef pthread_mutex_t vlc_mutex_t;
122 typedef pthread_cond_t vlc_cond_t;
123 typedef pthread_key_t vlc_threadvar_t;
125 #elif defined( WIN32 ) || defined( UNDER_CE )
129 void *(*entry) (void *);
133 typedef HANDLE vlc_mutex_t;
134 typedef HANDLE vlc_cond_t;
135 typedef DWORD vlc_threadvar_t;
137 #elif defined( SYS_BEOS )
138 /* This is the BeOS implementation of the vlc threads, note that the mutex is
139 * not a real mutex and the cond_var is not like a pthread cond_var but it is
140 * enough for what we need */
142 typedef thread_id vlc_thread_t;
162 #if defined( WIN32 ) && !defined ETIMEDOUT
163 # define ETIMEDOUT 10060 /* This is the value in winsock.h. */
166 /*****************************************************************************
167 * Function definitions
168 *****************************************************************************/
169 VLC_EXPORT( int, vlc_mutex_init, ( vlc_mutex_t * ) );
170 VLC_EXPORT( int, vlc_mutex_init_recursive, ( vlc_mutex_t * ) );
171 VLC_EXPORT( void, __vlc_mutex_destroy, ( const char *, int, vlc_mutex_t * ) );
172 VLC_EXPORT( int, __vlc_cond_init, ( vlc_cond_t * ) );
173 VLC_EXPORT( void, __vlc_cond_destroy, ( const char *, int, vlc_cond_t * ) );
174 VLC_EXPORT( int, vlc_threadvar_create, (vlc_threadvar_t * , void (*) (void *) ) );
175 VLC_EXPORT( void, vlc_threadvar_delete, (vlc_threadvar_t *) );
176 VLC_EXPORT( int, __vlc_thread_create, ( vlc_object_t *, const char *, int, const char *, void * ( * ) ( vlc_object_t * ), int, bool ) );
177 VLC_EXPORT( int, __vlc_thread_set_priority, ( vlc_object_t *, const char *, int, int ) );
178 VLC_EXPORT( void, __vlc_thread_join, ( vlc_object_t * ) );
180 VLC_EXPORT( int, vlc_clone, (vlc_thread_t *, void * (*) (void *), void *, int) );
181 VLC_EXPORT( void, vlc_cancel, (vlc_thread_t) );
182 VLC_EXPORT( void, vlc_join, (vlc_thread_t, void **) );
183 VLC_EXPORT (void, vlc_control_cancel, (int cmd, ...));
185 #ifndef LIBVLC_USE_PTHREAD_CANCEL
196 #define vlc_thread_ready vlc_object_signal
198 /*****************************************************************************
199 * vlc_mutex_lock: lock a mutex
200 *****************************************************************************/
201 #define vlc_mutex_lock( P_MUTEX ) \
202 __vlc_mutex_lock( __FILE__, __LINE__, P_MUTEX )
204 VLC_EXPORT(void, vlc_pthread_fatal, (const char *action, int error, const char *file, unsigned line));
206 #if defined(LIBVLC_USE_PTHREAD)
207 # define VLC_THREAD_ASSERT( action ) \
209 vlc_pthread_fatal (action, val, psz_file, i_line)
211 # define VLC_THREAD_ASSERT ((void)(val))
214 static inline void __vlc_mutex_lock( const char * psz_file, int i_line,
215 vlc_mutex_t * p_mutex )
217 #if defined(LIBVLC_USE_PTHREAD)
218 # define vlc_assert_locked( m ) \
219 assert (pthread_mutex_lock (m) == EDEADLK)
220 int val = pthread_mutex_lock( p_mutex );
221 VLC_THREAD_ASSERT ("locking mutex");
223 #elif defined( UNDER_CE )
224 (void)psz_file; (void)i_line;
226 EnterCriticalSection( &p_mutex->csection );
228 #elif defined( WIN32 )
229 (void)psz_file; (void)i_line;
231 WaitForSingleObject( *p_mutex, INFINITE );
233 #elif defined( SYS_BEOS )
234 acquire_sem( p_mutex->lock );
239 #ifndef vlc_assert_locked
240 # define vlc_assert_locked( m ) (void)m
243 /*****************************************************************************
244 * vlc_mutex_unlock: unlock a mutex
245 *****************************************************************************/
246 #define vlc_mutex_unlock( P_MUTEX ) \
247 __vlc_mutex_unlock( __FILE__, __LINE__, P_MUTEX )
249 static inline void __vlc_mutex_unlock( const char * psz_file, int i_line,
250 vlc_mutex_t *p_mutex )
252 #if defined(LIBVLC_USE_PTHREAD)
253 int val = pthread_mutex_unlock( p_mutex );
254 VLC_THREAD_ASSERT ("unlocking mutex");
256 #elif defined( UNDER_CE )
257 (void)psz_file; (void)i_line;
259 LeaveCriticalSection( &p_mutex->csection );
261 #elif defined( WIN32 )
262 (void)psz_file; (void)i_line;
264 ReleaseMutex( *p_mutex );
266 #elif defined( SYS_BEOS )
267 release_sem( p_mutex->lock );
272 /*****************************************************************************
273 * vlc_mutex_destroy: destroy a mutex
274 *****************************************************************************/
275 #define vlc_mutex_destroy( P_MUTEX ) \
276 __vlc_mutex_destroy( __FILE__, __LINE__, P_MUTEX )
279 * Save the cancellation state and disable cancellation for the calling thread.
280 * This function must be called before entering a piece of code that is not
282 * @return Previous cancellation state (opaque value).
284 static inline int vlc_savecancel (void)
287 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
288 (void) pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
290 vlc_control_cancel (VLC_SAVE_CANCEL, &state);
296 * Restore the cancellation state for the calling thread.
297 * @param state previous state as returned by vlc_savecancel().
298 * @return Nothing, always succeeds.
300 static inline void vlc_restorecancel (int state)
302 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
303 (void) pthread_setcancelstate (state, NULL);
305 vlc_control_cancel (VLC_RESTORE_CANCEL, state);
310 * Issues an explicit deferred cancellation point.
311 * This has no effect if thread cancellation is disabled.
312 * This can be called when there is a rather slow non-sleeping operation.
314 static inline void vlc_testcancel (void)
316 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
317 pthread_testcancel ();
319 vlc_control_cancel (VLC_TEST_CANCEL);
323 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
325 * Registers a new procedure to run if the thread is cancelled (or otherwise
326 * exits prematurely). Any call to vlc_cleanup_push() <b>must</b> paired with a
327 * call to either vlc_cleanup_pop() or vlc_cleanup_run(). Branching into or out
328 * of the block between these two function calls is not allowed (read: it will
329 * likely crash the whole process). If multiple procedures are registered,
330 * they are handled in last-in first-out order.
332 * @param routine procedure to call if the thread ends
333 * @param arg argument for the procedure
335 # define vlc_cleanup_push( routine, arg ) pthread_cleanup_push (routine, arg)
338 * Removes a cleanup procedure that was previously registered with
339 * vlc_cleanup_push().
341 # define vlc_cleanup_pop( ) pthread_cleanup_pop (0)
344 * Removes a cleanup procedure that was previously registered with
345 * vlc_cleanup_push(), and executes it.
347 # define vlc_cleanup_run( ) pthread_cleanup_pop (1)
349 typedef struct vlc_cleanup_t vlc_cleanup_t;
354 void (*proc) (void *);
358 /* This macros opens a code block on purpose. This is needed for multiple
359 * calls within a single function. This also prevent Win32 developpers from
360 * writing code that would break on POSIX (POSIX opens a block as well). */
361 # define vlc_cleanup_push( routine, arg ) \
363 vlc_cleanup_t vlc_cleanup_data = { NULL, routine, arg, }; \
364 vlc_control_cancel (VLC_CLEANUP_PUSH, &vlc_cleanup_data)
366 # define vlc_cleanup_pop( ) \
367 vlc_control_cancel (VLC_CLEANUP_POP); \
370 # define vlc_cleanup_run( ) \
371 vlc_control_cancel (VLC_CLEANUP_POP); \
372 vlc_cleanup_data.proc (vlc_cleanup_data.data); \
375 #endif /* LIBVLC_USE_PTHREAD_CANCEL */
377 static inline void vlc_cleanup_lock (void *lock)
379 vlc_mutex_unlock ((vlc_mutex_t *)lock);
381 #define mutex_cleanup_push( lock ) vlc_cleanup_push (vlc_cleanup_lock, lock)
383 /*****************************************************************************
384 * vlc_cond_init: initialize a condition
385 *****************************************************************************/
386 #define vlc_cond_init( P_THIS, P_COND ) \
387 __vlc_cond_init( P_COND )
389 /*****************************************************************************
390 * vlc_cond_signal: start a thread on condition completion
391 *****************************************************************************/
392 #define vlc_cond_signal( P_COND ) \
393 __vlc_cond_signal( __FILE__, __LINE__, P_COND )
395 static inline void __vlc_cond_signal( const char * psz_file, int i_line,
396 vlc_cond_t *p_condvar )
398 #if defined(LIBVLC_USE_PTHREAD)
399 int val = pthread_cond_signal( p_condvar );
400 VLC_THREAD_ASSERT ("signaling condition variable");
402 #elif defined( UNDER_CE ) || defined( WIN32 )
403 (void)psz_file; (void)i_line;
405 /* Release one waiting thread if one is available. */
406 /* For this trick to work properly, the vlc_cond_signal must be surrounded
407 * by a mutex. This will prevent another thread from stealing the signal */
408 /* PulseEvent() only works if none of the waiting threads is suspended.
409 * This is particularily problematic under a debug session.
410 * as documented in http://support.microsoft.com/kb/q173260/ */
411 PulseEvent( *p_condvar );
413 #elif defined( SYS_BEOS )
414 while( p_condvar->thread != -1 )
417 if( get_thread_info(p_condvar->thread, &info) == B_BAD_VALUE )
420 if( info.state != B_THREAD_SUSPENDED )
422 /* The waiting thread is not suspended so it could
423 * have been interrupted beetwen the unlock and the
424 * suspend_thread line. That is why we sleep a little
425 * before retesting p_condver->thread. */
430 /* Ok, we have to wake up that thread */
431 resume_thread( p_condvar->thread );
438 /*****************************************************************************
439 * vlc_cond_wait: wait until condition completion
440 *****************************************************************************/
441 #define vlc_cond_wait( P_COND, P_MUTEX ) \
442 __vlc_cond_wait( __FILE__, __LINE__, P_COND, P_MUTEX )
444 static inline void __vlc_cond_wait( const char * psz_file, int i_line,
445 vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex )
447 #if defined(LIBVLC_USE_PTHREAD)
448 int val = pthread_cond_wait( p_condvar, p_mutex );
449 VLC_THREAD_ASSERT ("waiting on condition");
451 #elif defined( UNDER_CE )
452 LeaveCriticalSection( &p_mutex->csection );
453 WaitForSingleObject( *p_condvar, INFINITE );
455 /* Reacquire the mutex before returning. */
456 vlc_mutex_lock( p_mutex );
458 #elif defined( WIN32 )
464 result = SignalObjectAndWait (*p_mutex, *p_condvar, INFINITE, TRUE);
466 /* Reacquire the mutex before returning. */
467 vlc_mutex_lock( p_mutex );
469 while (result == WAIT_IO_COMPLETION);
473 (void)psz_file; (void)i_line;
475 #elif defined( SYS_BEOS )
476 /* The p_condvar->thread var is initialized before the unlock because
477 * it enables to identify when the thread is interrupted beetwen the
478 * unlock line and the suspend_thread line */
479 p_condvar->thread = find_thread( NULL );
480 vlc_mutex_unlock( p_mutex );
481 suspend_thread( p_condvar->thread );
482 p_condvar->thread = -1;
484 vlc_mutex_lock( p_mutex );
490 /*****************************************************************************
491 * vlc_cond_timedwait: wait until condition completion or expiration
492 *****************************************************************************
493 * Returns 0 if object signaled, an error code in case of timeout or error.
494 *****************************************************************************/
495 #define vlc_cond_timedwait( P_COND, P_MUTEX, DEADLINE ) \
496 __vlc_cond_timedwait( __FILE__, __LINE__, P_COND, P_MUTEX, DEADLINE )
498 static inline int __vlc_cond_timedwait( const char * psz_file, int i_line,
499 vlc_cond_t *p_condvar,
500 vlc_mutex_t *p_mutex,
503 #if defined(LIBVLC_USE_PTHREAD)
504 lldiv_t d = lldiv( deadline, 1000000 );
505 struct timespec ts = { d.quot, d.rem * 1000 };
507 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
508 if (val != ETIMEDOUT)
509 VLC_THREAD_ASSERT ("timed-waiting on condition");
512 #elif defined( UNDER_CE )
513 mtime_t delay_ms = (deadline - mdate())/1000;
518 LeaveCriticalSection( &p_mutex->csection );
519 result = WaitForSingleObject( *p_condvar, delay_ms );
521 /* Reacquire the mutex before returning. */
522 vlc_mutex_lock( p_mutex );
524 (void)psz_file; (void)i_line;
526 return (result == WAIT_TIMEOUT) ? ETIMEDOUT : 0;
528 #elif defined( WIN32 )
530 DWORD result = WAIT_TIMEOUT;
532 (void)psz_file; (void)i_line;
535 while ((total = (deadline - mdate ()) > 0))
537 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
538 result = SignalObjectAndWait( *p_mutex, *p_condvar,
541 /* Reacquire the mutex before return/cancel. */
542 vlc_mutex_lock (p_mutex);
543 if (result == WAIT_OBJECT_0)
544 return 0; /* Condition signaled! */
549 #elif defined( SYS_BEOS )
550 # error Unimplemented
555 /*****************************************************************************
556 * vlc_cond_destroy: destroy a condition
557 *****************************************************************************/
558 #define vlc_cond_destroy( P_COND ) \
559 __vlc_cond_destroy( __FILE__, __LINE__, P_COND )
561 /*****************************************************************************
562 * vlc_threadvar_set: create: set the value of a thread-local variable
563 *****************************************************************************/
564 static inline int vlc_threadvar_set( vlc_threadvar_t * p_tls, void *p_value )
568 #if defined(LIBVLC_USE_PTHREAD)
569 i_ret = pthread_setspecific( *p_tls, p_value );
571 #elif defined( SYS_BEOS )
574 #elif defined( UNDER_CE ) || defined( WIN32 )
575 i_ret = TlsSetValue( *p_tls, p_value ) ? EINVAL : 0;
582 /*****************************************************************************
583 * vlc_threadvar_get: create: get the value of a thread-local variable
584 *****************************************************************************/
585 static inline void* vlc_threadvar_get( vlc_threadvar_t * p_tls )
589 #if defined(LIBVLC_USE_PTHREAD)
590 p_ret = pthread_getspecific( *p_tls );
592 #elif defined( SYS_BEOS )
595 #elif defined( UNDER_CE ) || defined( WIN32 )
596 p_ret = TlsGetValue( *p_tls );
603 # if defined (_POSIX_SPIN_LOCKS) && ((_POSIX_SPIN_LOCKS - 0) > 0)
604 typedef pthread_spinlock_t vlc_spinlock_t;
607 * Initializes a spinlock.
609 static inline int vlc_spin_init (vlc_spinlock_t *spin)
611 return pthread_spin_init (spin, PTHREAD_PROCESS_PRIVATE);
615 * Acquires a spinlock.
617 static inline void vlc_spin_lock (vlc_spinlock_t *spin)
619 pthread_spin_lock (spin);
623 * Releases a spinlock.
625 static inline void vlc_spin_unlock (vlc_spinlock_t *spin)
627 pthread_spin_unlock (spin);
631 * Deinitializes a spinlock.
633 static inline void vlc_spin_destroy (vlc_spinlock_t *spin)
635 pthread_spin_destroy (spin);
638 #elif defined( WIN32 )
640 typedef CRITICAL_SECTION vlc_spinlock_t;
643 * Initializes a spinlock.
645 static inline int vlc_spin_init (vlc_spinlock_t *spin)
647 return !InitializeCriticalSectionAndSpinCount(spin, 4000);
651 * Acquires a spinlock.
653 static inline void vlc_spin_lock (vlc_spinlock_t *spin)
655 EnterCriticalSection(spin);
659 * Releases a spinlock.
661 static inline void vlc_spin_unlock (vlc_spinlock_t *spin)
663 LeaveCriticalSection(spin);
667 * Deinitializes a spinlock.
669 static inline void vlc_spin_destroy (vlc_spinlock_t *spin)
671 DeleteCriticalSection(spin);
676 /* Fallback to plain mutexes if spinlocks are not available */
677 typedef vlc_mutex_t vlc_spinlock_t;
679 static inline int vlc_spin_init (vlc_spinlock_t *spin)
681 return vlc_mutex_init (spin);
684 # define vlc_spin_lock vlc_mutex_lock
685 # define vlc_spin_unlock vlc_mutex_unlock
686 # define vlc_spin_destroy vlc_mutex_destroy
690 * Issues a full memory barrier.
692 #if defined (__APPLE__)
693 # include <libkern/OSAtomic.h> /* OSMemoryBarrier() */
695 static inline void barrier (void)
697 #if defined (__GNUC__) && (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)
698 __sync_synchronize ();
699 #elif defined(__APPLE__)
701 #elif defined(__powerpc__)
702 asm volatile ("sync":::"memory");
703 #elif defined(__i386__)
704 asm volatile ("mfence":::"memory");
707 vlc_spin_init (&spin);
708 vlc_spin_lock (&spin);
709 vlc_spin_unlock (&spin);
710 vlc_spin_destroy (&spin);
714 /*****************************************************************************
715 * vlc_thread_create: create a thread
716 *****************************************************************************/
717 #define vlc_thread_create( P_THIS, PSZ_NAME, FUNC, PRIORITY, WAIT ) \
718 __vlc_thread_create( VLC_OBJECT(P_THIS), __FILE__, __LINE__, PSZ_NAME, FUNC, PRIORITY, WAIT )
720 /*****************************************************************************
721 * vlc_thread_set_priority: set the priority of the calling thread
722 *****************************************************************************/
723 #define vlc_thread_set_priority( P_THIS, PRIORITY ) \
724 __vlc_thread_set_priority( VLC_OBJECT(P_THIS), __FILE__, __LINE__, PRIORITY )
726 /*****************************************************************************
727 * vlc_thread_join: wait until a thread exits
728 *****************************************************************************/
729 #define vlc_thread_join( P_THIS ) \
730 __vlc_thread_join( VLC_OBJECT(P_THIS) )
732 #endif /* !_VLC_THREADS_H */