* ./include/vlc_threads.h: re-merged vlc_threads.h and threads_funcs.h.
[vlc.git] / include / vlc_threads.h
1 /*****************************************************************************
2  * threads.h : threads implementation for the VideoLAN client
3  * This header provides a portable threads implementation.
4  *****************************************************************************
5  * Copyright (C) 1999, 2000 VideoLAN
6  * $Id: vlc_threads.h,v 1.2 2002/06/02 13:38:03 gbazin Exp $
7  *
8  * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
9  *          Samuel Hocevar <sam@via.ecp.fr>
10  *          Gildas Bazin <gbazin@netcourrier.com>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  * 
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
25  *****************************************************************************/
26
27 #include <stdio.h>
28
29 #if defined(GPROF) || defined(DEBUG)
30 #   include <sys/time.h>
31 #endif
32
33 #if defined( PTH_INIT_IN_PTH_H )                                  /* GNU Pth */
34 #   include <pth.h>
35
36 #elif defined( ST_INIT_IN_ST_H )                            /* State threads */
37 #   include <st.h>
38
39 #elif defined( WIN32 )                                          /* Win32 API */
40 #   include <process.h>
41
42 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )  /* pthreads (like Linux & BSD) */
43 #   include <pthread.h>
44 #   ifdef DEBUG
45         /* Needed for pthread_cond_timedwait */
46 #       include <errno.h>
47 #   endif
48     /* This is not prototyped under Linux, though it exists. */
49     int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
50
51 #elif defined( HAVE_CTHREADS_H )                                  /* GNUMach */
52 #   include <cthreads.h>
53
54 #elif defined( HAVE_KERNEL_SCHEDULER_H )                             /* BeOS */
55 #   include <kernel/OS.h>
56 #   include <kernel/scheduler.h>
57 #   include <byteorder.h>
58
59 #else
60 #   error no threads available on your system !
61
62 #endif
63
64 /*****************************************************************************
65  * Constants
66  *****************************************************************************
67  * These constants are used by all threads in *_CreateThread() and
68  * *_DestroyThreads() functions. Since those calls are non-blocking, an integer
69  * value is used as a shared flag to represent the status of the thread.
70  *****************************************************************************/
71
72 /* Void status - this value can be used to make sure no operation is currently
73  * in progress on the concerned thread in an array of recorded threads */
74 #define THREAD_NOP          0                            /* nothing happened */
75
76 /* Creation status */
77 #define THREAD_CREATE       10                     /* thread is initializing */
78 #define THREAD_START        11                          /* thread has forked */
79 #define THREAD_READY        19                            /* thread is ready */
80
81 /* Destructions status */
82 #define THREAD_DESTROY      20            /* destruction order has been sent */
83 #define THREAD_END          21        /* destruction order has been received */
84 #define THREAD_OVER         29             /* thread does not exist any more */
85
86 /* Error status */
87 #define THREAD_ERROR        30                           /* an error occured */
88 #define THREAD_FATAL        31  /* an fatal error occured - program must end */
89
90 /*****************************************************************************
91  * Type definitions
92  *****************************************************************************/
93
94 #if defined( PTH_INIT_IN_PTH_H )
95 typedef pth_t            vlc_thread_t;
96 typedef pth_mutex_t      vlc_mutex_t;
97 typedef pth_cond_t       vlc_cond_t;
98
99 #elif defined( ST_INIT_IN_ST_H )
100 typedef st_thread_t *    vlc_thread_t;
101 typedef st_mutex_t *     vlc_mutex_t;
102 typedef st_cond_t *      vlc_cond_t;
103
104 #elif defined( WIN32 )
105 typedef HANDLE vlc_thread_t;
106 typedef BOOL (WINAPI *SIGNALOBJECTANDWAIT) ( HANDLE, HANDLE, DWORD, BOOL );
107 typedef unsigned (__stdcall *PTHREAD_START) (void *);
108
109 typedef struct
110 {
111     CRITICAL_SECTION    csection;
112     HANDLE              mutex;
113     SIGNALOBJECTANDWAIT SignalObjectAndWait;
114 } vlc_mutex_t;
115
116 typedef struct
117 {
118     int             i_waiting_threads;
119     HANDLE          signal;
120 } vlc_cond_t;
121
122 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
123 typedef pthread_t        vlc_thread_t;
124 typedef pthread_mutex_t  vlc_mutex_t;
125 typedef pthread_cond_t   vlc_cond_t;
126
127 #elif defined( HAVE_CTHREADS_H )
128 typedef cthread_t        vlc_thread_t;
129
130 /* Those structs are the ones defined in /include/cthreads.h but we need
131  * to handle (&foo) where foo is a (mutex_t) while they handle (foo) where
132  * foo is a (mutex_t*) */
133 typedef struct
134 {
135     spin_lock_t held;
136     spin_lock_t lock;
137     char *name;
138     struct cthread_queue queue;
139 } vlc_mutex_t;
140
141 typedef struct
142 {
143     spin_lock_t lock;
144     struct cthread_queue queue;
145     char *name;
146     struct cond_imp *implications;
147 } vlc_cond_t;
148
149 #elif defined( HAVE_KERNEL_SCHEDULER_H )
150 /* This is the BeOS implementation of the vlc threads, note that the mutex is
151  * not a real mutex and the cond_var is not like a pthread cond_var but it is
152  * enough for what wee need */
153
154 typedef thread_id vlc_thread_t;
155
156 typedef struct
157 {
158     int32           init;
159     sem_id          lock;
160 } vlc_mutex_t;
161
162 typedef struct
163 {
164     int32           init;
165     thread_id       thread;
166 } vlc_cond_t;
167
168 #endif
169
170 /*****************************************************************************
171  * Function definitions
172  *****************************************************************************/
173 VLC_EXPORT( int,  __vlc_threads_init,  ( vlc_object_t * ) );
174 VLC_EXPORT( int,    vlc_threads_end,   ( void ) );
175 VLC_EXPORT( int,  __vlc_mutex_init,    ( vlc_object_t *, vlc_mutex_t * ) );
176 VLC_EXPORT( int,  __vlc_mutex_destroy, ( char *, int, vlc_mutex_t * ) );
177 VLC_EXPORT( int,    vlc_cond_init,     ( vlc_cond_t * ) );
178 VLC_EXPORT( int,  __vlc_cond_destroy,  ( char *, int, vlc_cond_t * ) );
179 VLC_EXPORT( int,  __vlc_thread_create, ( vlc_object_t *, char *, int, char *, void * ( * ) ( void * ), vlc_bool_t ) );
180 VLC_EXPORT( void, __vlc_thread_ready,  ( vlc_object_t * ) );
181 VLC_EXPORT( void, __vlc_thread_join,   ( vlc_object_t *, char *, int ) );
182
183 /*****************************************************************************
184  * vlc_threads_init: initialize threads system
185  *****************************************************************************/
186 #define vlc_threads_init( P_THIS )                                          \
187     __vlc_threads_init( CAST_TO_VLC_OBJECT(P_THIS) )
188
189 /*****************************************************************************
190  * vlc_mutex_init: initialize a mutex
191  *****************************************************************************/
192 #define vlc_mutex_init( P_THIS, P_MUTEX )                                   \
193     __vlc_mutex_init( CAST_TO_VLC_OBJECT(P_THIS), P_MUTEX )
194
195 /*****************************************************************************
196  * vlc_mutex_lock: lock a mutex
197  *****************************************************************************/
198 #ifdef DEBUG
199 #   define vlc_mutex_lock( P_MUTEX )                                        \
200         __vlc_mutex_lock( __FILE__, __LINE__, P_MUTEX )
201 #else
202 #   define vlc_mutex_lock( P_MUTEX )                                        \
203         __vlc_mutex_lock( "(unknown)", 0, P_MUTEX )
204 #endif
205
206 static inline int __vlc_mutex_lock( char * psz_file, int i_line,
207                                     vlc_mutex_t *p_mutex )
208 {
209 #if defined( PTH_INIT_IN_PTH_H )
210     return pth_mutex_acquire( p_mutex, TRUE, NULL );
211
212 #elif defined( ST_INIT_IN_ST_H )
213     return st_mutex_lock( *p_mutex );
214
215 #elif defined( WIN32 )
216     if( p_mutex->mutex )
217     {
218         WaitForSingleObject( p_mutex->mutex, INFINITE );
219     }
220     else
221     {
222         EnterCriticalSection( &p_mutex->csection );
223     }
224     return 0;
225
226 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
227     int i_return = pthread_mutex_lock( p_mutex );
228     if( i_return )
229     {
230 //        msg_Err( "thread %d: mutex_lock failed at %s:%d (%s)",
231 //                 pthread_self(), psz_file, i_line, strerror(i_return) );
232     }
233     return i_return;
234
235 #elif defined( HAVE_CTHREADS_H )
236     mutex_lock( p_mutex );
237     return 0;
238
239 #elif defined( HAVE_KERNEL_SCHEDULER_H )
240     status_t err;
241
242     if( !p_mutex )
243     {
244         return B_BAD_VALUE;
245     }
246
247     if( p_mutex->init < 2000 )
248     {
249         return B_NO_INIT;
250     }
251
252     err = acquire_sem( p_mutex->lock );
253     return err;
254
255 #endif
256 }
257
258 /*****************************************************************************
259  * vlc_mutex_unlock: unlock a mutex
260  *****************************************************************************/
261 #ifdef DEBUG
262 #   define vlc_mutex_unlock( P_MUTEX )                                      \
263         __vlc_mutex_unlock( __FILE__, __LINE__, P_MUTEX )
264 #else
265 #   define vlc_mutex_unlock( P_MUTEX )                                      \
266         __vlc_mutex_unlock( "(unknown)", 0, P_MUTEX )
267 #endif
268
269 static inline int __vlc_mutex_unlock( char * psz_file, int i_line,
270                                       vlc_mutex_t *p_mutex )
271 {
272 #if defined( PTH_INIT_IN_PTH_H )
273     return pth_mutex_release( p_mutex );
274
275 #elif defined( ST_INIT_IN_ST_H )
276     return st_mutex_unlock( *p_mutex );
277
278 #elif defined( WIN32 )
279     if( p_mutex->mutex )
280     {
281         ReleaseMutex( p_mutex->mutex );
282     }
283     else
284     {
285         LeaveCriticalSection( &p_mutex->csection );
286     }
287     return 0;
288
289 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
290     int i_return = pthread_mutex_unlock( p_mutex );
291     if( i_return )
292     {
293 //        msg_Err( "thread %d: mutex_unlock failed at %s:%d (%s)",
294 //                 pthread_self(), psz_file, i_line, strerror(i_return) );
295     }
296     return i_return;
297
298 #elif defined( HAVE_CTHREADS_H )
299     mutex_unlock( p_mutex );
300     return 0;
301
302 #elif defined( HAVE_KERNEL_SCHEDULER_H )
303     if( !p_mutex)
304     {
305         return B_BAD_VALUE;
306     }
307
308     if( p_mutex->init < 2000 )
309     {
310         return B_NO_INIT;
311     }
312
313     release_sem( p_mutex->lock );
314     return B_OK;
315
316 #endif
317 }
318
319 /*****************************************************************************
320  * vlc_mutex_destroy: destroy a mutex
321  *****************************************************************************/
322 #ifdef DEBUG
323 #   define vlc_mutex_destroy( P_MUTEX )                                     \
324         __vlc_mutex_destroy( __FILE__, __LINE__, P_MUTEX )
325 #else
326 #   define vlc_mutex_destroy( P_MUTEX )                                     \
327         __vlc_mutex_destroy( "(unknown)", 0, P_MUTEX )
328 #endif
329
330 /*****************************************************************************
331  * vlc_cond_signal: start a thread on condition completion
332  *****************************************************************************/
333 static inline int vlc_cond_signal( vlc_cond_t *p_condvar )
334 {
335 #if defined( PTH_INIT_IN_PTH_H )
336     return pth_cond_notify( p_condvar, FALSE );
337
338 #elif defined( ST_INIT_IN_ST_H )
339     return st_cond_signal( *p_condvar );
340
341 #elif defined( WIN32 )
342     /* Release one waiting thread if one is available. */
343     /* For this trick to work properly, the vlc_cond_signal must be surrounded
344      * by a mutex. This will prevent another thread from stealing the signal */
345     PulseEvent( p_condvar->signal );
346     return 0;
347
348 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
349     return pthread_cond_signal( p_condvar );
350
351 #elif defined( HAVE_CTHREADS_H )
352     /* condition_signal() */
353     if ( p_condvar->queue.head || p_condvar->implications )
354     {
355         cond_signal( (condition_t)p_condvar );
356     }
357     return 0;
358
359 #elif defined( HAVE_KERNEL_SCHEDULER_H )
360     if( !p_condvar )
361     {
362         return B_BAD_VALUE;
363     }
364
365     if( p_condvar->init < 2000 )
366     {
367         return B_NO_INIT;
368     }
369
370     while( p_condvar->thread != -1 )
371     {
372         thread_info info;
373         if( get_thread_info(p_condvar->thread, &info) == B_BAD_VALUE )
374         {
375             return 0;
376         }
377
378         if( info.state != B_THREAD_SUSPENDED )
379         {
380             /* The  waiting thread is not suspended so it could
381              * have been interrupted beetwen the unlock and the
382              * suspend_thread line. That is why we sleep a little
383              * before retesting p_condver->thread. */
384             snooze( 10000 );
385         }
386         else
387         {
388             /* Ok, we have to wake up that thread */
389             resume_thread( p_condvar->thread );
390             return 0;
391         }
392     }
393     return 0;
394
395 #endif
396 }
397
398 /*****************************************************************************
399  * vlc_cond_broadcast: start all threads waiting on condition completion
400  *****************************************************************************/
401 /*
402  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
403  * Only works with pthreads, you need to adapt it for others
404  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
405  */
406 static inline int vlc_cond_broadcast( vlc_cond_t *p_condvar )
407 {
408 #if defined( PTH_INIT_IN_PTH_H )
409     return pth_cond_notify( p_condvar, FALSE );
410
411 #elif defined( ST_INIT_IN_ST_H )
412     return st_cond_broadcast( p_condvar );
413
414 #elif defined( WIN32 )
415     /* Release all waiting threads. */
416     while( p_condvar->i_waiting_threads )
417     {
418         PulseEvent( p_condvar->signal );
419         Sleep( 1 ); /* deschedule the current thread */
420     }
421     return 0;
422
423 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
424     return pthread_cond_broadcast( p_condvar );
425
426 #elif defined( HAVE_CTHREADS_H )
427     /* condition_signal() */
428     if ( p_condvar->queue.head || p_condvar->implications )
429     {
430         cond_signal( (condition_t)p_condvar );
431     }
432     return 0;
433
434 #elif defined( HAVE_KERNEL_SCHEDULER_H )
435     if( !p_condvar )
436     {
437         return B_BAD_VALUE;
438     }
439
440     if( p_condvar->init < 2000 )
441     {
442         return B_NO_INIT;
443     }
444
445     while( p_condvar->thread != -1 )
446     {
447         thread_info info;
448         if( get_thread_info(p_condvar->thread, &info) == B_BAD_VALUE )
449         {
450             return 0;
451         }
452
453         if( info.state != B_THREAD_SUSPENDED )
454         {
455             /* The  waiting thread is not suspended so it could
456              * have been interrupted beetwen the unlock and the
457              * suspend_thread line. That is why we sleep a little
458              * before retesting p_condver->thread. */
459             snooze( 10000 );
460         }
461         else
462         {
463             /* Ok, we have to wake up that thread */
464             resume_thread( p_condvar->thread );
465             return 0;
466         }
467     }
468     return 0;
469
470 #endif
471 }
472
473 /*****************************************************************************
474  * vlc_cond_wait: wait until condition completion
475  *****************************************************************************/
476 #ifdef DEBUG
477 #   define vlc_cond_wait( P_COND, P_MUTEX )                                   \
478         __vlc_cond_wait( __FILE__, __LINE__, P_COND, P_MUTEX  )
479 #else
480 #   define vlc_cond_wait( P_COND, P_MUTEX )                                   \
481         __vlc_cond_wait( "(unknown)", 0, P_COND, P_MUTEX )
482 #endif
483
484 static inline int __vlc_cond_wait( char * psz_file, int i_line,
485                                    vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex )
486 {
487 #if defined( PTH_INIT_IN_PTH_H )
488     return pth_cond_await( p_condvar, p_mutex, NULL );
489
490 #elif defined( ST_INIT_IN_ST_H )
491     int i_ret;
492
493     st_mutex_unlock( *p_mutex );
494     i_ret = st_cond_wait( *p_condvar );
495     st_mutex_lock( *p_mutex );
496
497     return i_ret;
498
499 #elif defined( WIN32 )
500     /* It is only possible to atomically release the mutex and initiate the
501      * waiting on WinNT/2K/XP. Win9x doesn't have SignalObjectAndWait().
502      */
503     int i_result;
504
505     p_condvar->i_waiting_threads ++;
506
507     if( p_mutex->mutex )
508     {
509         p_mutex->SignalObjectAndWait( p_mutex->mutex, p_condvar->signal,
510                                       INFINITE, FALSE );
511     }
512     else
513     {
514         /* Release the mutex */
515         vlc_mutex_unlock( p_mutex );
516         i_result = WaitForSingleObject( p_condvar->signal, INFINITE); 
517         p_condvar->i_waiting_threads --;
518     }
519
520     /* Reacquire the mutex before returning. */
521     vlc_mutex_lock( p_mutex );
522
523     return( i_result == WAIT_FAILED );
524
525 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
526
527 #   ifdef DEBUG
528     /* In debug mode, timeout */
529     struct timeval now;
530     struct timespec timeout;
531     int    i_result;
532
533     for( ; ; )
534     {
535         gettimeofday( &now, NULL );
536         timeout.tv_sec = now.tv_sec + THREAD_COND_TIMEOUT;
537         timeout.tv_nsec = now.tv_usec * 1000;
538
539         i_result = pthread_cond_timedwait( p_condvar, p_mutex, &timeout );
540
541         if( i_result == ETIMEDOUT )
542         {
543 //X            msg_Warn( "thread %d: possible deadlock detected "
544 //X                      "in cond_wait at %s:%d (%s)", pthread_self(),
545 //X                      psz_file, i_line, strerror(i_result) );
546             continue;
547         }
548
549         if( i_result )
550         {
551 //X            msg_Err( "thread %d: cond_wait failed at %s:%d (%s)",
552 //X                     pthread_self(), psz_file, i_line, strerror(i_result) );
553         }
554         return( i_result );
555     }
556 #   else
557     return pthread_cond_wait( p_condvar, p_mutex );
558 #   endif
559
560 #elif defined( HAVE_CTHREADS_H )
561     condition_wait( (condition_t)p_condvar, (mutex_t)p_mutex );
562     return 0;
563
564 #elif defined( HAVE_KERNEL_SCHEDULER_H )
565     if( !p_condvar )
566     {
567         return B_BAD_VALUE;
568     }
569
570     if( !p_mutex )
571     {
572         return B_BAD_VALUE;
573     }
574
575     if( p_condvar->init < 2000 )
576     {
577         return B_NO_INIT;
578     }
579
580     /* The p_condvar->thread var is initialized before the unlock because
581      * it enables to identify when the thread is interrupted beetwen the
582      * unlock line and the suspend_thread line */
583     p_condvar->thread = find_thread( NULL );
584     vlc_mutex_unlock( p_mutex );
585     suspend_thread( p_condvar->thread );
586     p_condvar->thread = -1;
587
588     vlc_mutex_lock( p_mutex );
589     return 0;
590
591 #endif
592 }
593
594 /*****************************************************************************
595  * vlc_cond_destroy: destroy a condition
596  *****************************************************************************/
597 #ifdef DEBUG
598 #   define vlc_cond_destroy( P_COND )                                       \
599         __vlc_cond_destroy( __FILE__, __LINE__, P_COND )
600 #else
601 #   define vlc_cond_destroy( P_COND )                                       \
602         __vlc_cond_destroy( "(unknown)", 0, P_COND )
603 #endif
604
605 /*****************************************************************************
606  * vlc_thread_create: create a thread
607  *****************************************************************************/
608 #   define vlc_thread_create( P_THIS, PSZ_NAME, FUNC, WAIT )                \
609         __vlc_thread_create( CAST_TO_VLC_OBJECT(P_THIS), __FILE__, __LINE__, PSZ_NAME, (void * ( * ) ( void * ))FUNC, WAIT )
610
611 /*****************************************************************************
612  * vlc_thread_ready: tell the parent thread we were successfully spawned
613  *****************************************************************************/
614 #   define vlc_thread_ready( P_THIS )                                       \
615         __vlc_thread_ready( CAST_TO_VLC_OBJECT(P_THIS) )
616
617 /*****************************************************************************
618  * vlc_thread_join: wait until a thread exits
619  *****************************************************************************/
620 #ifdef DEBUG
621 #   define vlc_thread_join( P_THIS )                                        \
622         __vlc_thread_join( CAST_TO_VLC_OBJECT(P_THIS), __FILE__, __LINE__ ) 
623 #else
624 #   define vlc_thread_join( P_THIS )                                        \
625         __vlc_thread_join( CAST_TO_VLC_OBJECT(P_THIS), "(unknown)", 0 ) 
626 #endif