* New pthread implementation for WinNT/2K/XP. This implementation shouldn't
[vlc.git] / include / 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: threads.h,v 1.39 2002/04/02 23:43:57 gbazin Exp $
7  *
8  * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
9  *          Samuel Hocevar <sam@via.ecp.fr>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  * 
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 #include <stdio.h>
27
28 #if defined(GPROF) || defined(DEBUG)
29 #   include <sys/time.h>
30 #endif
31
32 #if defined( PTH_INIT_IN_PTH_H )                                  /* GNU Pth */
33 #   include <pth.h>
34
35 #elif defined( ST_INIT_IN_ST_H )                            /* State threads */
36 #   include <st.h>
37
38 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )  /* pthreads (like Linux & BSD) */
39 #   include <pthread.h>
40 #   ifdef DEBUG
41 /* Needed for pthread_cond_timedwait */
42 #       include <errno.h>
43 #   endif
44 /* This is not prototyped under Linux, though it exists. */
45 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
46
47 #elif defined( HAVE_CTHREADS_H )                                  /* GNUMach */
48 #   include <cthreads.h>
49
50 #elif defined( HAVE_KERNEL_SCHEDULER_H )                             /* BeOS */
51 #   include <kernel/OS.h>
52 #   include <kernel/scheduler.h>
53 #   include <byteorder.h>
54
55 #elif defined( WIN32 )
56 #   include <process.h>
57
58 #else
59 #   error no threads available on your system !
60
61 #endif
62
63 /*****************************************************************************
64  * Constants
65  *****************************************************************************
66  * These constants are used by all threads in *_CreateThread() and
67  * *_DestroyThreads() functions. Since those calls are non-blocking, an integer
68  * value is used as a shared flag to represent the status of the thread.
69  *****************************************************************************/
70
71 /* Void status - this value can be used to make sure no operation is currently
72  * in progress on the concerned thread in an array of recorded threads */
73 #define THREAD_NOP          0                            /* nothing happened */
74
75 /* Creation status */
76 #define THREAD_CREATE       10                     /* thread is initializing */
77 #define THREAD_START        11                          /* thread has forked */
78 #define THREAD_READY        19                            /* thread is ready */
79
80 /* Destructions status */
81 #define THREAD_DESTROY      20            /* destruction order has been sent */
82 #define THREAD_END          21        /* destruction order has been received */
83 #define THREAD_OVER         29             /* thread does not exist any more */
84
85 /* Error status */
86 #define THREAD_ERROR        30                           /* an error occured */
87 #define THREAD_FATAL        31  /* an fatal error occured - program must end */
88
89 /*****************************************************************************
90  * Types definition
91  *****************************************************************************/
92
93 #if defined( PTH_INIT_IN_PTH_H )
94 typedef pth_t            vlc_thread_t;
95 typedef pth_mutex_t      vlc_mutex_t;
96 typedef pth_cond_t       vlc_cond_t;
97
98 #elif defined( ST_INIT_IN_ST_H )
99 typedef st_thread_t *    vlc_thread_t;
100 typedef st_mutex_t *     vlc_mutex_t;
101 typedef st_cond_t *      vlc_cond_t;
102
103 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
104 typedef pthread_t        vlc_thread_t;
105 typedef pthread_mutex_t  vlc_mutex_t;
106 typedef pthread_cond_t   vlc_cond_t;
107
108 #elif defined( HAVE_CTHREADS_H )
109 typedef cthread_t        vlc_thread_t;
110
111 /* Those structs are the ones defined in /include/cthreads.h but we need
112  * to handle (*foo) where foo is a (mutex_t) while they handle (foo) where
113  * foo is a (mutex_t*) */
114 typedef struct s_mutex {
115     spin_lock_t held;
116     spin_lock_t lock;
117     char *name;
118     struct cthread_queue queue;
119 } vlc_mutex_t;
120
121 typedef struct s_condition {
122     spin_lock_t lock;
123     struct cthread_queue queue;
124     char *name;
125     struct cond_imp *implications;
126 } vlc_cond_t;
127
128 #elif defined( HAVE_KERNEL_SCHEDULER_H )
129 /* This is the BeOS implementation of the vlc threads, note that the mutex is
130  * not a real mutex and the cond_var is not like a pthread cond_var but it is
131  * enough for what wee need */
132
133 typedef thread_id vlc_thread_t;
134
135 typedef struct
136 {
137     int32           init;
138     sem_id          lock;
139 } vlc_mutex_t;
140
141 typedef struct
142 {
143     int32           init;
144     thread_id       thread;
145 } vlc_cond_t;
146
147 #elif defined( WIN32 )
148 typedef HANDLE vlc_thread_t;
149
150 typedef struct
151 {
152     CRITICAL_SECTION csection;
153     HANDLE           mutex;
154 } vlc_mutex_t;
155
156 typedef struct
157 {
158     int             i_waiting_threads;
159     HANDLE          signal;
160 } vlc_cond_t;
161
162 typedef unsigned (__stdcall *PTHREAD_START) (void *);
163
164 #endif
165
166 typedef void *(*vlc_thread_func_t)(void *p_data);
167
168 /*****************************************************************************
169  * Prototypes
170  *****************************************************************************/
171
172 #ifdef GPROF
173 /* Wrapper function for profiling */
174 static void *      vlc_thread_wrapper ( void *p_wrapper );
175
176 #   ifdef WIN32
177
178 #       define ITIMER_REAL 1
179 #       define ITIMER_PROF 2
180
181 struct itimerval
182 {
183     struct timeval it_value;
184     struct timeval it_interval;
185 };
186
187 int setitimer(int kind, const struct itimerval* itnew, struct itimerval* itold);
188
189 #   endif /* WIN32 */
190
191 typedef struct wrapper_s
192 {
193     /* Data lock access */
194     vlc_mutex_t lock;
195     vlc_cond_t  wait;
196
197     /* Data used to spawn the real thread */
198     vlc_thread_func_t func;
199     void *p_data;
200
201     /* Profiling timer passed to the thread */
202     struct itimerval itimer;
203
204 } wrapper_t;
205
206 #endif /* GPROF */
207
208 /*****************************************************************************
209  * vlc_threads_init: initialize threads system
210  *****************************************************************************/
211 static __inline__ int vlc_threads_init( void )
212 {
213 #if defined( PTH_INIT_IN_PTH_H )
214     return pth_init();
215
216 #elif defined( ST_INIT_IN_ST_H )
217     return st_init();
218
219 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
220     return 0;
221
222 #elif defined( HAVE_CTHREADS_H )
223     return 0;
224
225 #elif defined( HAVE_KERNEL_SCHEDULER_H )
226     return 0;
227
228 #elif defined( WIN32 )
229     return 0;
230
231 #endif
232 }
233
234 /*****************************************************************************
235  * vlc_threads_end: stop threads system
236  *****************************************************************************/
237 static __inline__ int vlc_threads_end( void )
238 {
239 #if defined( PTH_INIT_IN_PTH_H )
240     return pth_kill();
241
242 #elif defined( ST_INIT_IN_ST_H )
243     return 0;
244
245 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
246     return 0;
247
248 #elif defined( HAVE_CTHREADS_H )
249     return 0;
250
251 #elif defined( HAVE_KERNEL_SCHEDULER_H )
252     return 0;
253
254 #elif defined( WIN32 )
255     return 0;
256
257 #endif
258 }
259
260 /*****************************************************************************
261  * vlc_mutex_init: initialize a mutex
262  *****************************************************************************/
263 static __inline__ int vlc_mutex_init( vlc_mutex_t *p_mutex )
264 {
265 #if defined( PTH_INIT_IN_PTH_H )
266     return pth_mutex_init( p_mutex );
267
268 #elif defined( ST_INIT_IN_ST_H )
269     *p_mutex = st_mutex_new();
270     return ( *p_mutex == NULL ) ? errno : 0;
271
272 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
273 #   if defined(DEBUG) && defined(SYS_LINUX)
274     /* Create error-checking mutex to detect threads problems more easily. */
275     pthread_mutexattr_t attr;
276     int                 i_result;
277
278     pthread_mutexattr_init( &attr );
279     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
280     i_result = pthread_mutex_init( p_mutex, &attr );
281     pthread_mutexattr_destroy( &attr );
282     return( i_result );
283 #   endif
284
285     return pthread_mutex_init( p_mutex, NULL );
286
287 #elif defined( HAVE_CTHREADS_H )
288     mutex_init( p_mutex );
289     return 0;
290
291 #elif defined( HAVE_KERNEL_SCHEDULER_H )
292
293     /* check the arguments and whether it's already been initialized */
294     if( p_mutex == NULL )
295     {
296         return B_BAD_VALUE;
297     }
298
299     if( p_mutex->init == 9999 )
300     {
301         return EALREADY;
302     }
303
304     p_mutex->lock = create_sem( 1, "BeMutex" );
305     if( p_mutex->lock < B_NO_ERROR )
306     {
307         return( -1 );
308     }
309
310     p_mutex->init = 9999;
311     return B_OK;
312
313 #elif defined( WIN32 )
314     /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
315      * function and have a 100% correct vlc_cond_wait() implementation.
316      * As this function is not available on Win9x, we can use the faster
317      * CriticalSections */
318     if( (GetVersion() < 0x80000000) && !p_main_sys->b_fast_pthread )
319     {
320         /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
321         p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
322         return ( p_mutex->mutex ? 0 : 1 );
323     }
324     else
325     {
326         InitializeCriticalSection( &p_mutex->csection );
327         p_mutex->mutex = NULL;
328         return 0;
329     }
330
331 #endif
332 }
333
334 /*****************************************************************************
335  * vlc_mutex_lock: lock a mutex
336  *****************************************************************************/
337 #ifdef DEBUG
338 #   define vlc_mutex_lock( P_MUTEX )                                        \
339         _vlc_mutex_lock( __FILE__, __LINE__, P_MUTEX )
340 #else
341 #   define vlc_mutex_lock( P_MUTEX )                                        \
342         _vlc_mutex_lock( NULL, 0, P_MUTEX )
343 #endif
344
345 static __inline__ int _vlc_mutex_lock( char * psz_file, int i_line,
346                                        vlc_mutex_t *p_mutex )
347 {
348 #if defined( PTH_INIT_IN_PTH_H )
349     return pth_mutex_acquire( p_mutex, TRUE, NULL );
350
351 #elif defined( ST_INIT_IN_ST_H )
352     return st_mutex_lock( *p_mutex );
353
354 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
355     int i_return = pthread_mutex_lock( p_mutex );
356     if( i_return )
357     {
358         intf_ErrMsg( "thread %d error: mutex_lock failed at %s:%d (%s)",
359                      pthread_self(), psz_file, i_line, strerror(i_return) );
360     }
361     return i_return;
362
363 #elif defined( HAVE_CTHREADS_H )
364     mutex_lock( p_mutex );
365     return 0;
366
367 #elif defined( HAVE_KERNEL_SCHEDULER_H )
368     status_t err;
369
370     if( !p_mutex )
371     {
372         return B_BAD_VALUE;
373     }
374
375     if( p_mutex->init < 2000 )
376     {
377         return B_NO_INIT;
378     }
379
380     err = acquire_sem( p_mutex->lock );
381     return err;
382
383 #elif defined( WIN32 )
384     if( p_mutex->mutex )
385     {
386         WaitForSingleObject( p_mutex->mutex, INFINITE );
387     }
388     else
389     {
390         EnterCriticalSection( &p_mutex->csection );
391     }
392     return 0;
393
394 #endif
395 }
396
397 /*****************************************************************************
398  * vlc_mutex_unlock: unlock a mutex
399  *****************************************************************************/
400 #ifdef DEBUG
401 #   define vlc_mutex_unlock( P_MUTEX )                                      \
402         _vlc_mutex_unlock( __FILE__, __LINE__, P_MUTEX )
403 #else
404 #   define vlc_mutex_unlock( P_MUTEX )                                      \
405         _vlc_mutex_unlock( NULL, 0, P_MUTEX )
406 #endif
407
408 static __inline__ int _vlc_mutex_unlock( char * psz_file, int i_line,
409                                          vlc_mutex_t *p_mutex )
410 {
411 #if defined( PTH_INIT_IN_PTH_H )
412     return pth_mutex_release( p_mutex );
413
414 #elif defined( ST_INIT_IN_ST_H )
415     return st_mutex_unlock( *p_mutex );
416
417 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
418     int i_return = pthread_mutex_unlock( p_mutex );
419     if( i_return )
420     {
421         intf_ErrMsg( "thread %d error: mutex_unlock failed at %s:%d (%s)",
422                      pthread_self(), psz_file, i_line, strerror(i_return) );
423     }
424     return i_return;
425
426 #elif defined( HAVE_CTHREADS_H )
427     mutex_unlock( p_mutex );
428     return 0;
429
430 #elif defined( HAVE_KERNEL_SCHEDULER_H )
431     if( !p_mutex)
432     {
433         return B_BAD_VALUE;
434     }
435
436     if( p_mutex->init < 2000 )
437     {
438         return B_NO_INIT;
439     }
440
441     release_sem( p_mutex->lock );
442     return B_OK;
443
444 #elif defined( WIN32 )
445     if( p_mutex->mutex )
446     {
447         ReleaseMutex( p_mutex->mutex );
448     }
449     else
450     {
451         LeaveCriticalSection( &p_mutex->csection );
452     }
453     return 0;
454
455 #endif
456 }
457
458 /*****************************************************************************
459  * vlc_mutex_destroy: destroy a mutex
460  *****************************************************************************/
461 #ifdef DEBUG
462 #   define vlc_mutex_destroy( P_MUTEX )                                     \
463         _vlc_mutex_destroy( __FILE__, __LINE__, P_MUTEX )
464 #else
465 #   define vlc_mutex_destroy( P_MUTEX )                                     \
466         _vlc_mutex_destroy( NULL, 0, P_MUTEX )
467 #endif
468
469 static __inline__ int _vlc_mutex_destroy( char * psz_file, int i_line,
470                                           vlc_mutex_t *p_mutex )
471 {
472 #if defined( PTH_INIT_IN_PTH_H )
473     return 0;
474
475 #elif defined( ST_INIT_IN_ST_H )
476     return st_mutex_destroy( *p_mutex );
477
478 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )    
479     int i_return = pthread_mutex_destroy( p_mutex );
480     if( i_return )
481     {
482         intf_ErrMsg( "thread %d error: mutex_destroy failed at %s:%d (%s)",
483                      pthread_self(), psz_file, i_line, strerror(i_return) );
484     }
485     return i_return;
486
487 #elif defined( HAVE_CTHREADS_H )
488     return 0;
489
490 #elif defined( HAVE_KERNEL_SCHEDULER_H )
491     if( p_mutex->init == 9999 )
492     {
493         delete_sem( p_mutex->lock );
494     }
495
496     p_mutex->init = 0;
497     return B_OK;
498
499 #elif defined( WIN32 )
500     if( p_mutex->mutex )
501     {
502         CloseHandle( p_mutex->mutex );
503     }
504     else
505     {
506         DeleteCriticalSection( &p_mutex->csection );
507     }
508     return 0;
509
510 #endif    
511 }
512
513 /*****************************************************************************
514  * vlc_cond_init: initialize a condition
515  *****************************************************************************/
516 static __inline__ int vlc_cond_init( vlc_cond_t *p_condvar )
517 {
518 #if defined( PTH_INIT_IN_PTH_H )
519     return pth_cond_init( p_condvar );
520
521 #elif defined( ST_INIT_IN_ST_H )
522     *p_condvar = st_cond_new();
523     return ( *p_condvar == NULL ) ? errno : 0;
524
525 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
526     return pthread_cond_init( p_condvar, NULL );
527
528 #elif defined( HAVE_CTHREADS_H )
529     /* condition_init() */
530     spin_lock_init( &p_condvar->lock );
531     cthread_queue_init( &p_condvar->queue );
532     p_condvar->name = 0;
533     p_condvar->implications = 0;
534
535     return 0;
536
537 #elif defined( HAVE_KERNEL_SCHEDULER_H )
538     if( !p_condvar )
539     {
540         return B_BAD_VALUE;
541     }
542
543     if( p_condvar->init == 9999 )
544     {
545         return EALREADY;
546     }
547
548     p_condvar->thread = -1;
549     p_condvar->init = 9999;
550     return 0;
551
552 #elif defined( WIN32 )
553     /* initialise counter */
554     p_condvar->i_waiting_threads = 0;
555
556     /* Create an auto-reset event. */
557     p_condvar->signal = CreateEvent( NULL, /* no security */
558                                      FALSE,  /* auto-reset event */
559                                      FALSE,  /* non-signaled initially */
560                                      NULL ); /* unnamed */
561
562     return( !p_condvar->signal );
563     
564 #endif
565 }
566
567 /*****************************************************************************
568  * vlc_cond_signal: start a thread on condition completion
569  *****************************************************************************/
570 static __inline__ int vlc_cond_signal( vlc_cond_t *p_condvar )
571 {
572 #if defined( PTH_INIT_IN_PTH_H )
573     return pth_cond_notify( p_condvar, FALSE );
574
575 #elif defined( ST_INIT_IN_ST_H )
576     return st_cond_signal( *p_condvar );
577
578 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
579     return pthread_cond_signal( p_condvar );
580
581 #elif defined( HAVE_CTHREADS_H )
582     /* condition_signal() */
583     if ( p_condvar->queue.head || p_condvar->implications )
584     {
585         cond_signal( (condition_t)p_condvar );
586     }
587     return 0;
588
589 #elif defined( HAVE_KERNEL_SCHEDULER_H )
590     if( !p_condvar )
591     {
592         return B_BAD_VALUE;
593     }
594
595     if( p_condvar->init < 2000 )
596     {
597         return B_NO_INIT;
598     }
599
600     while( p_condvar->thread != -1 )
601     {
602         thread_info info;
603         if( get_thread_info(p_condvar->thread, &info) == B_BAD_VALUE )
604         {
605             return 0;
606         }
607
608         if( info.state != B_THREAD_SUSPENDED )
609         {
610             /* The  waiting thread is not suspended so it could
611              * have been interrupted beetwen the unlock and the
612              * suspend_thread line. That is why we sleep a little
613              * before retesting p_condver->thread. */
614             snooze( 10000 );
615         }
616         else
617         {
618             /* Ok, we have to wake up that thread */
619             resume_thread( p_condvar->thread );
620             return 0;
621         }
622     }
623     return 0;
624
625 #elif defined( WIN32 )
626     /* Release one waiting thread if one is available. */
627     /* For this trick to work properly, the vlc_cond_signal must be surrounded
628      * by a mutex. This will prevent another thread from stealing the signal */
629     PulseEvent( p_condvar->signal );
630     return 0;
631
632 #endif
633 }
634
635 /*****************************************************************************
636  * vlc_cond_broadcast: start all threads waiting on condition completion
637  *****************************************************************************/
638 /*
639  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
640  * Only works with pthreads, you need to adapt it for others
641  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
642  */
643 static __inline__ int vlc_cond_broadcast( vlc_cond_t *p_condvar )
644 {
645 #if defined( PTH_INIT_IN_PTH_H )
646     return pth_cond_notify( p_condvar, FALSE );
647
648 #elif defined( ST_INIT_IN_ST_H )
649     return st_cond_broadcast( p_condvar );
650
651 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
652     return pthread_cond_broadcast( p_condvar );
653
654 #elif defined( HAVE_CTHREADS_H )
655     /* condition_signal() */
656     if ( p_condvar->queue.head || p_condvar->implications )
657     {
658         cond_signal( (condition_t)p_condvar );
659     }
660     return 0;
661
662 #elif defined( HAVE_KERNEL_SCHEDULER_H )
663     if( !p_condvar )
664     {
665         return B_BAD_VALUE;
666     }
667
668     if( p_condvar->init < 2000 )
669     {
670         return B_NO_INIT;
671     }
672
673     while( p_condvar->thread != -1 )
674     {
675         thread_info info;
676         if( get_thread_info(p_condvar->thread, &info) == B_BAD_VALUE )
677         {
678             return 0;
679         }
680
681         if( info.state != B_THREAD_SUSPENDED )
682         {
683             /* The  waiting thread is not suspended so it could
684              * have been interrupted beetwen the unlock and the
685              * suspend_thread line. That is why we sleep a little
686              * before retesting p_condver->thread. */
687             snooze( 10000 );
688         }
689         else
690         {
691             /* Ok, we have to wake up that thread */
692             resume_thread( p_condvar->thread );
693             return 0;
694         }
695     }
696     return 0;
697
698 #elif defined( WIN32 )
699     /* Release all waiting threads. */
700     /* For this trick to work properly, the vlc_cond_signal must be surrounded
701      * by a mutex. This will prevent another thread from stealing the signal */
702     while( p_condvar->i_waiting_threads )
703     {
704         PulseEvent( p_condvar->signal );
705         Sleep( 1 ); /* deschedule the current thread */
706     }
707     return 0;
708
709 #endif
710 }
711
712 /*****************************************************************************
713  * vlc_cond_wait: wait until condition completion
714  *****************************************************************************/
715 #ifdef DEBUG
716 #   define vlc_cond_wait( P_COND, P_MUTEX )                                 \
717         _vlc_cond_wait( __FILE__, __LINE__, P_COND, P_MUTEX  )
718 #else
719 #   define vlc_cond_wait( P_COND, P_MUTEX )                                 \
720         _vlc_cond_wait( NULL, 0, P_COND, P_MUTEX )
721 #endif
722
723 static __inline__ int _vlc_cond_wait( char * psz_file, int i_line,
724                                       vlc_cond_t *p_condvar,
725                                       vlc_mutex_t *p_mutex )
726 {
727 #if defined( PTH_INIT_IN_PTH_H )
728     return pth_cond_await( p_condvar, p_mutex, NULL );
729
730 #elif defined( ST_INIT_IN_ST_H )
731     int i_ret;
732
733     st_mutex_unlock( *p_mutex );
734     i_ret = st_cond_wait( *p_condvar );
735     st_mutex_lock( *p_mutex );
736
737     return i_ret;
738
739 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
740
741 #ifndef DEBUG
742     return pthread_cond_wait( p_condvar, p_mutex );
743 #else
744     /* In debug mode, timeout */
745     struct timeval now;
746     struct timespec timeout;
747     int    i_result;
748
749     for( ; ; )
750     {
751         gettimeofday( &now, NULL );
752         timeout.tv_sec = now.tv_sec + THREAD_COND_TIMEOUT;
753         timeout.tv_nsec = now.tv_usec * 1000;
754
755         i_result = pthread_cond_timedwait( p_condvar, p_mutex, &timeout );
756
757         if( i_result == ETIMEDOUT )
758         {
759             intf_WarnMsg( 1, "thread %d warning: Possible deadlock detected in cond_wait at %s:%d (%s)",
760                           pthread_self(), psz_file, i_line, strerror(i_result) );
761             continue;
762         }
763
764         if( i_result )
765         {
766             intf_ErrMsg( "thread %d error: cond_wait failed at %s:%d (%s)",
767                          pthread_self(), psz_file, i_line, strerror(i_result) );
768         }
769         return( i_result );
770     }
771 #endif
772
773 #elif defined( HAVE_CTHREADS_H )
774     condition_wait( (condition_t)p_condvar, (mutex_t)p_mutex );
775     return 0;
776
777 #elif defined( HAVE_KERNEL_SCHEDULER_H )
778     if( !p_condvar )
779     {
780         return B_BAD_VALUE;
781     }
782
783     if( !p_mutex )
784     {
785         return B_BAD_VALUE;
786     }
787
788     if( p_condvar->init < 2000 )
789     {
790         return B_NO_INIT;
791     }
792
793     /* The p_condvar->thread var is initialized before the unlock because
794      * it enables to identify when the thread is interrupted beetwen the
795      * unlock line and the suspend_thread line */
796     p_condvar->thread = find_thread( NULL );
797     vlc_mutex_unlock( p_mutex );
798     suspend_thread( p_condvar->thread );
799     p_condvar->thread = -1;
800
801     vlc_mutex_lock( p_mutex );
802     return 0;
803
804 #elif defined( WIN32 )
805     /* The ideal would be to use a function which atomically releases the
806      * mutex and initiate the waiting.
807      * Unfortunately only the SignalObjectAndWait function does this and it's
808      * only supported on WinNT/2K, furthermore it cannot take multiple
809      * events as parameters.
810      *
811      * The solution we use should however fulfill all our needs (even though
812      * it is not a correct pthreads implementation)
813      */
814     int i_result;
815
816     p_condvar->i_waiting_threads ++;
817
818     if( p_mutex->mutex )
819     {
820         p_main_sys->SignalObjectAndWait( p_mutex->mutex, p_condvar->signal,
821                                          INFINITE, FALSE );
822     }
823     else
824     {
825         /* Release the mutex */
826         vlc_mutex_unlock( p_mutex );
827         i_result = WaitForSingleObject( p_condvar->signal, INFINITE); 
828         p_condvar->i_waiting_threads --;
829     }
830
831     /* Reacquire the mutex before returning. */
832     vlc_mutex_lock( p_mutex );
833
834     return( i_result == WAIT_FAILED );
835
836 #endif
837 }
838
839 /*****************************************************************************
840  * vlc_cond_destroy: destroy a condition
841  *****************************************************************************/
842 #ifdef DEBUG
843 #   define vlc_cond_destroy( P_COND )                                       \
844         _vlc_cond_destroy( __FILE__, __LINE__, P_COND )
845 #else
846 #   define vlc_cond_destroy( P_COND )                                       \
847         _vlc_cond_destroy( NULL, 0, P_COND )
848 #endif
849
850 static __inline__ int _vlc_cond_destroy( char * psz_file, int i_line,
851                                          vlc_cond_t *p_condvar )
852 {
853 #if defined( PTH_INIT_IN_PTH_H )
854     return 0;
855
856 #elif defined( ST_INIT_IN_ST_H )
857     return st_cond_destroy( *p_condvar );
858
859 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
860     int i_result = pthread_cond_destroy( p_condvar );
861     if( i_result )
862     {
863         intf_ErrMsg( "thread %d error: cond_destroy failed at %s:%d (%s)",
864                      pthread_self(), psz_file, i_line, strerror(i_result) );
865     }
866     return i_result;
867
868 #elif defined( HAVE_CTHREADS_H )
869     return 0;
870
871 #elif defined( HAVE_KERNEL_SCHEDULER_H )
872     p_condvar->init = 0;
873     return 0;
874
875 #elif defined( WIN32 )
876     return( !CloseHandle( p_condvar->signal ) );
877
878 #endif    
879 }
880
881 /*****************************************************************************
882  * vlc_thread_create: create a thread
883  *****************************************************************************/
884 #ifdef DEBUG
885 #   define vlc_thread_create( P_THREAD, PSZ_NAME, FUNC, P_DATA )            \
886         _vlc_thread_create( __FILE__, __LINE__, P_THREAD, PSZ_NAME, FUNC, P_DATA )
887 #else
888 #   define vlc_thread_create( P_THREAD, PSZ_NAME, FUNC, P_DATA )            \
889         _vlc_thread_create( NULL, 0, P_THREAD, PSZ_NAME, FUNC, P_DATA )
890 #endif
891
892 static __inline__ int _vlc_thread_create( char * psz_file, int i_line,
893                                           vlc_thread_t *p_thread,
894                                           char *psz_name,
895                                           vlc_thread_func_t func,
896                                           void *p_data )
897 {
898     int i_ret;
899
900 #ifdef GPROF
901     wrapper_t wrapper;
902
903     /* Initialize the wrapper structure */
904     wrapper.func = func;
905     wrapper.p_data = p_data;
906     getitimer( ITIMER_PROF, &wrapper.itimer );
907     vlc_mutex_init( &wrapper.lock );
908     vlc_cond_init( &wrapper.wait );
909     vlc_mutex_lock( &wrapper.lock );
910
911     /* Alter user-passed data so that we call the wrapper instead
912      * of the real function */
913     p_data = &wrapper;
914     func = vlc_thread_wrapper;
915 #endif
916
917 #if defined( PTH_INIT_IN_PTH_H )
918     *p_thread = pth_spawn( PTH_ATTR_DEFAULT, func, p_data );
919     i_ret = ( p_thread == NULL );
920
921 #elif defined( ST_INIT_IN_ST_H )
922     *p_thread = st_thread_create( func, p_data, 1, 0 );
923     i_ret = ( p_thread == NULL );
924     
925 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
926     i_ret = pthread_create( p_thread, NULL, func, p_data );
927
928 #elif defined( HAVE_CTHREADS_H )
929     *p_thread = cthread_fork( (cthread_fn_t)func, (any_t)p_data );
930     i_ret = 0;
931
932 #elif defined( HAVE_KERNEL_SCHEDULER_H )
933     *p_thread = spawn_thread( (thread_func)func, psz_name,
934                               B_NORMAL_PRIORITY, p_data );
935     i_ret = resume_thread( *p_thread );
936
937 #elif defined( WIN32 )
938     unsigned threadID;
939     /* When using the MSVCRT C library you have to use the _beginthreadex
940      * function instead of CreateThread, otherwise you'll end up with memory
941      * leaks and the signal functions not working */
942     *p_thread = (HANDLE)_beginthreadex( NULL, 0, (PTHREAD_START) func, 
943                                         p_data, 0, &threadID );
944     
945     i_ret = ( *p_thread ? 0 : 1 );
946
947 #endif
948
949 #ifdef GPROF
950     if( i_ret == 0 )
951     {
952         vlc_cond_wait( &wrapper.wait, &wrapper.lock );
953     }
954
955     vlc_mutex_unlock( &wrapper.lock );
956     vlc_mutex_destroy( &wrapper.lock );
957     vlc_cond_destroy( &wrapper.wait );
958 #endif
959
960     if( i_ret == 0 )
961     {
962         intf_WarnMsg( 2, "thread info: %d (%s) has been created (%s:%d)",
963                       *p_thread, psz_name, psz_file, i_line );
964     }
965     else
966     {
967         intf_ErrMsg( "thread error: %s couldn't be created at %s:%d (%s)",
968                      psz_name, psz_file, i_line, strerror(i_ret) );
969     }
970
971     return i_ret;
972 }
973
974 /*****************************************************************************
975  * vlc_thread_exit: terminate a thread
976  *****************************************************************************/
977 static __inline__ void vlc_thread_exit( void )
978 {
979 #if defined( PTH_INIT_IN_PTH_H )
980     pth_exit( 0 );
981
982 #elif defined( ST_INIT_IN_ST_H )
983     int result;
984     st_thread_exit( &result );
985     
986 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
987     pthread_exit( 0 );
988
989 #elif defined( HAVE_CTHREADS_H )
990     int result;
991     cthread_exit( &result );
992
993 #elif defined( HAVE_KERNEL_SCHEDULER_H )
994     exit_thread( 0 );
995
996 #elif defined( WIN32 )
997     /* For now we don't close the thread handles (because of race conditions).
998      * Need to be looked at. */
999     _endthreadex(0);
1000
1001 #endif
1002 }
1003
1004 /*****************************************************************************
1005  * vlc_thread_join: wait until a thread exits
1006  *****************************************************************************/
1007 #ifdef DEBUG
1008 #   define vlc_thread_join( THREAD )                                        \
1009         _vlc_thread_join( __FILE__, __LINE__, THREAD ) 
1010 #else
1011 #   define vlc_thread_join( THREAD )                                        \
1012         _vlc_thread_join( NULL, 0, THREAD ) 
1013 #endif
1014
1015 static __inline__ void _vlc_thread_join( char * psz_file, int i_line,
1016                                          vlc_thread_t thread )
1017 {
1018     int i_ret = 0;
1019
1020 #if defined( PTH_INIT_IN_PTH_H )
1021     i_ret = pth_join( thread, NULL );
1022
1023 #elif defined( ST_INIT_IN_ST_H )
1024     i_ret = st_thread_join( thread, NULL );
1025     
1026 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
1027     i_ret = pthread_join( thread, NULL );
1028
1029 #elif defined( HAVE_CTHREADS_H )
1030     cthread_join( thread );
1031     i_ret = 1;
1032
1033 #elif defined( HAVE_KERNEL_SCHEDULER_H )
1034     int32 exit_value;
1035     wait_for_thread( thread, &exit_value );
1036
1037 #elif defined( WIN32 )
1038     WaitForSingleObject( thread, INFINITE );
1039
1040 #endif
1041
1042     if( i_ret )
1043     {
1044         intf_ErrMsg( "thread error: thread_join(%d) failed at %s:%d (%s)",
1045                      thread, psz_file, i_line, strerror(i_ret) );
1046     }
1047     else
1048     {
1049         intf_WarnMsg( 2, "thread info: %d has been joined (%s:%d)",
1050                       thread, psz_file, i_line );
1051     }
1052 }
1053
1054 #ifdef GPROF
1055 static void *vlc_thread_wrapper( void *p_wrapper )
1056 {
1057     /* Put user data in thread-local variables */
1058     void *            p_data = ((wrapper_t*)p_wrapper)->p_data;
1059     vlc_thread_func_t func   = ((wrapper_t*)p_wrapper)->func;
1060
1061     /* Set the profile timer value */
1062     setitimer( ITIMER_PROF, &((wrapper_t*)p_wrapper)->itimer, NULL );
1063
1064     /* Tell the calling thread that we don't need its data anymore */
1065     vlc_mutex_lock( &((wrapper_t*)p_wrapper)->lock );
1066     vlc_cond_signal( &((wrapper_t*)p_wrapper)->wait );
1067     vlc_mutex_unlock( &((wrapper_t*)p_wrapper)->lock );
1068
1069     /* Call the real function */
1070     return func( p_data );
1071 }
1072 #endif