]> git.sesse.net Git - vlc/blob - include/vlc_threads.h
vlc_threads.h: gather per-platform support
[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 VLC authors and VideoLAN
6  * Copyright © 2007-2008 Rémi Denis-Courmont
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 it
14  * under the terms of the GNU Lesser General Public License as published by
15  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * 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 (WIN32)
38 # include <process.h>
39 # ifndef ETIMEDOUT
40 #  define ETIMEDOUT 10060 /* This is the value in winsock.h. */
41 # endif
42
43 typedef struct vlc_thread *vlc_thread_t;
44 typedef struct
45 {
46     bool dynamic;
47     union
48     {
49         struct
50         {
51             bool locked;
52             unsigned long contention;
53         };
54         CRITICAL_SECTION mutex;
55     };
56 } vlc_mutex_t;
57 #define VLC_STATIC_MUTEX { false, { { false, 0 } } }
58 typedef struct
59 {
60     HANDLE   handle;
61     unsigned clock;
62 } vlc_cond_t;
63 #define VLC_STATIC_COND { 0, 0 }
64 typedef HANDLE vlc_sem_t;
65 #define LIBVLC_NEED_RWLOCK
66 typedef struct vlc_threadvar *vlc_threadvar_t;
67 typedef struct vlc_timer *vlc_timer_t;
68
69 # define VLC_THREAD_PRIORITY_LOW      0
70 # define VLC_THREAD_PRIORITY_INPUT    THREAD_PRIORITY_ABOVE_NORMAL
71 # define VLC_THREAD_PRIORITY_AUDIO    THREAD_PRIORITY_HIGHEST
72 # define VLC_THREAD_PRIORITY_VIDEO    0
73 # define VLC_THREAD_PRIORITY_OUTPUT   THREAD_PRIORITY_ABOVE_NORMAL
74 # define VLC_THREAD_PRIORITY_HIGHEST  THREAD_PRIORITY_TIME_CRITICAL
75
76 #elif defined (__OS2__)
77 # include <errno.h>
78
79 typedef struct vlc_thread *vlc_thread_t;
80 typedef struct
81 {
82     bool dynamic;
83     union
84     {
85         struct
86         {
87             bool locked;
88             unsigned long contention;
89         };
90         HMTX hmtx;
91     };
92 } vlc_mutex_t;
93 #define VLC_STATIC_MUTEX { false, { { false, 0 } } }
94 typedef struct
95 {
96     HEV      hev;
97     unsigned clock;
98 } vlc_cond_t;
99 #define VLC_STATIC_COND { 0, 0 }
100 #define LIBVLC_NEED_SEMAPHORE
101 #define LIBVLC_NEED_RWLOCK
102 typedef struct vlc_threadvar *vlc_threadvar_t;
103 typedef struct vlc_timer *vlc_timer_t;
104
105 # define VLC_THREAD_PRIORITY_LOW      0
106 # define VLC_THREAD_PRIORITY_INPUT \
107                                     MAKESHORT(PRTYD_MAXIMUM / 2, PRTYC_REGULAR)
108 # define VLC_THREAD_PRIORITY_AUDIO    MAKESHORT(PRTYD_MAXIMUM, PRTYC_REGULAR)
109 # define VLC_THREAD_PRIORITY_VIDEO    0
110 # define VLC_THREAD_PRIORITY_OUTPUT \
111                                     MAKESHORT(PRTYD_MAXIMUM / 2, PRTYC_REGULAR)
112 # define VLC_THREAD_PRIORITY_HIGHEST  MAKESHORT(0, PRTYC_TIMECRITICAL)
113
114 # define pthread_sigmask  sigprocmask
115
116 #elif defined (__ANDROID__)      /* pthreads subset without pthread_cancel() */
117 # include <unistd.h>
118 # include <pthread.h>
119 # include <poll.h>
120 # define LIBVLC_USE_PTHREAD_CLEANUP   1
121 # define LIBVLC_NEED_SEMAPHORE
122 # define LIBVLC_NEED_RWLOCK
123
124 typedef struct vlc_thread *vlc_thread_t;
125 typedef pthread_mutex_t vlc_mutex_t;
126 #define VLC_STATIC_MUTEX PTHREAD_MUTEX_INITIALIZER
127 typedef pthread_cond_t  vlc_cond_t;
128 #define VLC_STATIC_COND  PTHREAD_COND_INITIALIZER
129
130 typedef pthread_key_t   vlc_threadvar_t;
131 typedef struct vlc_timer *vlc_timer_t;
132
133 # define VLC_THREAD_PRIORITY_LOW      0
134 # define VLC_THREAD_PRIORITY_INPUT    0
135 # define VLC_THREAD_PRIORITY_AUDIO    0
136 # define VLC_THREAD_PRIORITY_VIDEO    0
137 # define VLC_THREAD_PRIORITY_OUTPUT   0
138 # define VLC_THREAD_PRIORITY_HIGHEST  0
139
140 #elif defined (__APPLE__)
141 # define _APPLE_C_SOURCE    1 /* Proper pthread semantics on OSX */
142 # include <unistd.h>
143 # include <pthread.h>
144 /* Unnamed POSIX semaphores not supported on Mac OS X */
145 # include <mach/semaphore.h>
146 # include <mach/task.h>
147 # include <libkern/OSAtomic.h> /* OSMemoryBarrier() */
148 # define LIBVLC_USE_PTHREAD           1
149 # define LIBVLC_USE_PTHREAD_CLEANUP   1
150 # define LIBVLC_USE_PTHREAD_CANCEL    1
151
152 typedef pthread_t       vlc_thread_t;
153 typedef pthread_mutex_t vlc_mutex_t;
154 #define VLC_STATIC_MUTEX PTHREAD_MUTEX_INITIALIZER
155 typedef pthread_cond_t  vlc_cond_t;
156 #define VLC_STATIC_COND  PTHREAD_COND_INITIALIZER
157 typedef semaphore_t     vlc_sem_t;
158 typedef pthread_rwlock_t vlc_rwlock_t;
159 #define VLC_STATIC_RWLOCK PTHREAD_RWLOCK_INITIALIZER
160 typedef pthread_key_t   vlc_threadvar_t;
161 typedef struct vlc_timer *vlc_timer_t;
162
163 # define VLC_THREAD_PRIORITY_LOW      0
164 # define VLC_THREAD_PRIORITY_INPUT   22
165 # define VLC_THREAD_PRIORITY_AUDIO   22
166 # define VLC_THREAD_PRIORITY_VIDEO    0
167 # define VLC_THREAD_PRIORITY_OUTPUT  22
168 # define VLC_THREAD_PRIORITY_HIGHEST 22
169
170 #else /* POSIX threads */
171 # include <unistd.h> /* _POSIX_SPIN_LOCKS */
172 # include <pthread.h>
173 # include <semaphore.h>
174 # define LIBVLC_USE_PTHREAD           1
175 # define LIBVLC_USE_PTHREAD_CLEANUP   1
176 # define LIBVLC_USE_PTHREAD_CANCEL    1
177
178 typedef pthread_t       vlc_thread_t;
179 typedef pthread_mutex_t vlc_mutex_t;
180 #define VLC_STATIC_MUTEX PTHREAD_MUTEX_INITIALIZER
181 typedef pthread_cond_t  vlc_cond_t;
182 #define VLC_STATIC_COND  PTHREAD_COND_INITIALIZER
183 typedef sem_t           vlc_sem_t;
184 typedef pthread_rwlock_t vlc_rwlock_t;
185 #define VLC_STATIC_RWLOCK PTHREAD_RWLOCK_INITIALIZER
186 typedef pthread_key_t   vlc_threadvar_t;
187 typedef struct vlc_timer *vlc_timer_t;
188
189 # define VLC_THREAD_PRIORITY_LOW      0
190 # define VLC_THREAD_PRIORITY_INPUT   10
191 # define VLC_THREAD_PRIORITY_AUDIO    5
192 # define VLC_THREAD_PRIORITY_VIDEO    0
193 # define VLC_THREAD_PRIORITY_OUTPUT  15
194 # define VLC_THREAD_PRIORITY_HIGHEST 20
195
196 #endif
197
198 #ifdef LIBVLC_NEED_SEMAPHORE
199 typedef struct vlc_sem
200 {
201     vlc_mutex_t lock;
202     vlc_cond_t  wait;
203     unsigned    value;
204 } vlc_sem_t;
205 #endif
206
207 #ifdef LIBVLC_NEED_RWLOCK
208 typedef struct vlc_rwlock
209 {
210     vlc_mutex_t   mutex;
211     vlc_cond_t    wait;
212     long          state;
213 } vlc_rwlock_t;
214 # define VLC_STATIC_RWLOCK { VLC_STATIC_MUTEX, VLC_STATIC_COND, 0 }
215 #endif
216
217 /*****************************************************************************
218  * Function definitions
219  *****************************************************************************/
220 VLC_API void vlc_mutex_init( vlc_mutex_t * );
221 VLC_API void vlc_mutex_init_recursive( vlc_mutex_t * );
222 VLC_API void vlc_mutex_destroy( vlc_mutex_t * );
223 VLC_API void vlc_mutex_lock( vlc_mutex_t * );
224 VLC_API int vlc_mutex_trylock( vlc_mutex_t * ) VLC_USED;
225 VLC_API void vlc_mutex_unlock( vlc_mutex_t * );
226 VLC_API void vlc_cond_init( vlc_cond_t * );
227 VLC_API void vlc_cond_init_daytime( vlc_cond_t * );
228 VLC_API void vlc_cond_destroy( vlc_cond_t * );
229 VLC_API void vlc_cond_signal(vlc_cond_t *);
230 VLC_API void vlc_cond_broadcast(vlc_cond_t *);
231 VLC_API void vlc_cond_wait(vlc_cond_t *, vlc_mutex_t *);
232 VLC_API int vlc_cond_timedwait(vlc_cond_t *, vlc_mutex_t *, mtime_t);
233 VLC_API void vlc_sem_init(vlc_sem_t *, unsigned);
234 VLC_API void vlc_sem_destroy(vlc_sem_t *);
235 VLC_API int vlc_sem_post(vlc_sem_t *);
236 VLC_API void vlc_sem_wait(vlc_sem_t *);
237
238 VLC_API void vlc_rwlock_init(vlc_rwlock_t *);
239 VLC_API void vlc_rwlock_destroy(vlc_rwlock_t *);
240 VLC_API void vlc_rwlock_rdlock(vlc_rwlock_t *);
241 VLC_API void vlc_rwlock_wrlock(vlc_rwlock_t *);
242 VLC_API void vlc_rwlock_unlock(vlc_rwlock_t *);
243 VLC_API int vlc_threadvar_create(vlc_threadvar_t * , void (*) (void *) );
244 VLC_API void vlc_threadvar_delete(vlc_threadvar_t *);
245 VLC_API int vlc_threadvar_set(vlc_threadvar_t, void *);
246 VLC_API void * vlc_threadvar_get(vlc_threadvar_t);
247
248 VLC_API int vlc_clone(vlc_thread_t *, void * (*) (void *), void *, int) VLC_USED;
249 VLC_API void vlc_cancel(vlc_thread_t);
250 VLC_API void vlc_join(vlc_thread_t, void **);
251 VLC_API void vlc_control_cancel (int cmd, ...);
252
253 VLC_API mtime_t mdate(void);
254 VLC_API void mwait(mtime_t deadline);
255 VLC_API void msleep(mtime_t delay);
256
257 #define VLC_HARD_MIN_SLEEP   10000 /* 10 milliseconds = 1 tick at 100Hz */
258 #define VLC_SOFT_MIN_SLEEP 9000000 /* 9 seconds */
259
260 #if VLC_GCC_VERSION(4,3)
261 /* Linux has 100, 250, 300 or 1000Hz
262  *
263  * HZ=100 by default on FreeBSD, but some architectures use a 1000Hz timer
264  */
265
266 static
267 __attribute__((unused))
268 __attribute__((noinline))
269 __attribute__((error("sorry, cannot sleep for such short a time")))
270 mtime_t impossible_delay( mtime_t delay )
271 {
272     (void) delay;
273     return VLC_HARD_MIN_SLEEP;
274 }
275
276 static
277 __attribute__((unused))
278 __attribute__((noinline))
279 __attribute__((warning("use proper event handling instead of short delay")))
280 mtime_t harmful_delay( mtime_t delay )
281 {
282     return delay;
283 }
284
285 # define check_delay( d ) \
286     ((__builtin_constant_p(d < VLC_HARD_MIN_SLEEP) \
287    && (d < VLC_HARD_MIN_SLEEP)) \
288        ? impossible_delay(d) \
289        : ((__builtin_constant_p(d < VLC_SOFT_MIN_SLEEP) \
290        && (d < VLC_SOFT_MIN_SLEEP)) \
291            ? harmful_delay(d) \
292            : d))
293
294 static
295 __attribute__((unused))
296 __attribute__((noinline))
297 __attribute__((error("deadlines can not be constant")))
298 mtime_t impossible_deadline( mtime_t deadline )
299 {
300     return deadline;
301 }
302
303 # define check_deadline( d ) \
304     (__builtin_constant_p(d) ? impossible_deadline(d) : d)
305 #else
306 # define check_delay(d) (d)
307 # define check_deadline(d) (d)
308 #endif
309
310 #define msleep(d) msleep(check_delay(d))
311 #define mwait(d) mwait(check_deadline(d))
312
313 VLC_API int vlc_timer_create(vlc_timer_t *, void (*) (void *), void *) VLC_USED;
314 VLC_API void vlc_timer_destroy(vlc_timer_t);
315 VLC_API void vlc_timer_schedule(vlc_timer_t, bool, mtime_t, mtime_t);
316 VLC_API unsigned vlc_timer_getoverrun(vlc_timer_t) VLC_USED;
317
318 VLC_API unsigned vlc_GetCPUCount(void);
319
320 VLC_API int vlc_savecancel(void);
321 VLC_API void vlc_restorecancel(int state);
322 VLC_API void vlc_testcancel(void);
323
324 #if defined (LIBVLC_USE_PTHREAD_CLEANUP)
325 /**
326  * Registers a new procedure to run if the thread is cancelled (or otherwise
327  * exits prematurely). Any call to vlc_cleanup_push() <b>must</b> paired with a
328  * call to either vlc_cleanup_pop() or vlc_cleanup_run(). Branching into or out
329  * of the block between these two function calls is not allowed (read: it will
330  * likely crash the whole process). If multiple procedures are registered,
331  * they are handled in last-in first-out order.
332  *
333  * @param routine procedure to call if the thread ends
334  * @param arg argument for the procedure
335  */
336 # define vlc_cleanup_push( routine, arg ) pthread_cleanup_push (routine, arg)
337
338 /**
339  * Removes a cleanup procedure that was previously registered with
340  * vlc_cleanup_push().
341  */
342 # define vlc_cleanup_pop( ) pthread_cleanup_pop (0)
343
344 /**
345  * Removes a cleanup procedure that was previously registered with
346  * vlc_cleanup_push(), and executes it.
347  */
348 # define vlc_cleanup_run( ) pthread_cleanup_pop (1)
349
350 #else
351 enum
352 {
353     VLC_CLEANUP_PUSH,
354     VLC_CLEANUP_POP,
355 };
356 typedef struct vlc_cleanup_t vlc_cleanup_t;
357
358 struct vlc_cleanup_t
359 {
360     vlc_cleanup_t *next;
361     void         (*proc) (void *);
362     void          *data;
363 };
364
365 /* This macros opens a code block on purpose. This is needed for multiple
366  * calls within a single function. This also prevent Win32 developers from
367  * writing code that would break on POSIX (POSIX opens a block as well). */
368 # define vlc_cleanup_push( routine, arg ) \
369     do { \
370         vlc_cleanup_t vlc_cleanup_data = { NULL, routine, arg, }; \
371         vlc_control_cancel (VLC_CLEANUP_PUSH, &vlc_cleanup_data)
372
373 # define vlc_cleanup_pop( ) \
374         vlc_control_cancel (VLC_CLEANUP_POP); \
375     } while (0)
376
377 # define vlc_cleanup_run( ) \
378         vlc_control_cancel (VLC_CLEANUP_POP); \
379         vlc_cleanup_data.proc (vlc_cleanup_data.data); \
380     } while (0)
381
382 #endif /* !LIBVLC_USE_PTHREAD_CLEANUO */
383
384 #ifndef LIBVLC_USE_PTHREAD_CANCEL
385 /* poll() with cancellation */
386 static inline int vlc_poll (struct pollfd *fds, unsigned nfds, int timeout)
387 {
388     vlc_testcancel ();
389
390     while (timeout > 50)
391     {
392         int val = poll (fds, nfds, timeout);
393         if (val != 0)
394             return val;
395         timeout -= 50;
396         vlc_testcancel ();
397     }
398
399     return poll (fds, nfds, timeout);
400 }
401 # define poll(u,n,t) vlc_poll(u, n, t)
402
403 #endif /* LIBVLC_USE_PTHREAD_CANCEL */
404
405 static inline void vlc_cleanup_lock (void *lock)
406 {
407     vlc_mutex_unlock ((vlc_mutex_t *)lock);
408 }
409 #define mutex_cleanup_push( lock ) vlc_cleanup_push (vlc_cleanup_lock, lock)
410
411 #if defined (_POSIX_SPIN_LOCKS) && ((_POSIX_SPIN_LOCKS - 0) > 0)
412 typedef pthread_spinlock_t vlc_spinlock_t;
413
414 /**
415  * Initializes a spinlock.
416  */
417 static inline void vlc_spin_init (vlc_spinlock_t *spin)
418 {
419     if (pthread_spin_init (spin, PTHREAD_PROCESS_PRIVATE))
420         abort ();
421 }
422
423 /**
424  * Acquires a spinlock.
425  */
426 static inline void vlc_spin_lock (vlc_spinlock_t *spin)
427 {
428     pthread_spin_lock (spin);
429 }
430
431 /**
432  * Releases a spinlock.
433  */
434 static inline void vlc_spin_unlock (vlc_spinlock_t *spin)
435 {
436     pthread_spin_unlock (spin);
437 }
438
439 /**
440  * Deinitializes a spinlock.
441  */
442 static inline void vlc_spin_destroy (vlc_spinlock_t *spin)
443 {
444     pthread_spin_destroy (spin);
445 }
446
447 #elif defined (WIN32)
448 typedef CRITICAL_SECTION vlc_spinlock_t;
449
450 static inline void vlc_spin_init (vlc_spinlock_t *spin)
451 {
452     if (!InitializeCriticalSectionAndSpinCount(spin, 4000))
453         abort ();
454 }
455
456 static inline void vlc_spin_lock (vlc_spinlock_t *spin)
457 {
458     EnterCriticalSection(spin);
459 }
460
461 static inline void vlc_spin_unlock (vlc_spinlock_t *spin)
462 {
463     LeaveCriticalSection(spin);
464 }
465
466 static inline void vlc_spin_destroy (vlc_spinlock_t *spin)
467 {
468     DeleteCriticalSection(spin);
469 }
470
471 #else
472 /* Fallback to plain mutexes if spinlocks are not available */
473 typedef vlc_mutex_t vlc_spinlock_t;
474
475 static inline void vlc_spin_init (vlc_spinlock_t *spin)
476 {
477     vlc_mutex_init (spin);
478 }
479
480 # define vlc_spin_lock    vlc_mutex_lock
481 # define vlc_spin_unlock  vlc_mutex_unlock
482 # define vlc_spin_destroy vlc_mutex_destroy
483 #endif
484
485 /**
486  * Issues a full memory barrier.
487  */
488 static inline void barrier (void)
489 {
490 #if defined (__GNUC__) && !defined (__APPLE__) && \
491             ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1))
492     __sync_synchronize ();
493 #elif defined(__APPLE__)
494     OSMemoryBarrier ();
495 #elif defined(__powerpc__)
496     asm volatile ("sync":::"memory");
497 #elif 0 // defined(__i386__) /*  Requires SSE2 support */
498     asm volatile ("mfence":::"memory");
499 #else
500     vlc_spinlock_t spin;
501     vlc_spin_init (&spin);
502     vlc_spin_lock (&spin);
503     vlc_spin_unlock (&spin);
504     vlc_spin_destroy (&spin);
505 #endif
506 }
507
508 #ifdef __cplusplus
509 /**
510  * Helper C++ class to lock a mutex.
511  * The mutex is locked when the object is created, and unlocked when the object
512  * is destroyed.
513  */
514 class vlc_mutex_locker
515 {
516     private:
517         vlc_mutex_t *lock;
518     public:
519         vlc_mutex_locker (vlc_mutex_t *m) : lock (m)
520         {
521             vlc_mutex_lock (lock);
522         }
523
524         ~vlc_mutex_locker (void)
525         {
526             vlc_mutex_unlock (lock);
527         }
528 };
529 #endif
530
531 enum
532 {
533    VLC_AVCODEC_MUTEX = 0,
534    VLC_GCRYPT_MUTEX,
535    VLC_XLIB_MUTEX,
536    VLC_MOSAIC_MUTEX,
537    VLC_HIGHLIGHT_MUTEX,
538    VLC_ATOMIC_MUTEX,
539    /* Insert new entry HERE */
540    VLC_MAX_MUTEX
541 };
542
543 VLC_API void vlc_global_mutex( unsigned, bool );
544 #define vlc_global_lock( n ) vlc_global_mutex( n, true )
545 #define vlc_global_unlock( n ) vlc_global_mutex( n, false )
546
547 #endif /* !_VLC_THREADS_H */