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