]> git.sesse.net Git - vlc/blob - include/threads.h
* ./include/threads.h: support for the State Threads Library, a userland
[vlc] / 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.35 2002/02/25 23:59:07 sam 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 /* This is not prototyped under Linux, though it exists. */
41 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
42
43 #elif defined( HAVE_CTHREADS_H )                                  /* GNUMach */
44 #   include <cthreads.h>
45
46 #elif defined( HAVE_KERNEL_SCHEDULER_H )                             /* BeOS */
47 #   undef MAX
48 #   undef MIN
49 #   include <kernel/OS.h>
50 #   include <kernel/scheduler.h>
51 #   include <byteorder.h>
52
53 #elif defined( WIN32 )
54 #define WIN32_LEAN_AND_MEAN
55 #   include <windows.h>
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 typedef CRITICAL_SECTION vlc_mutex_t;
150
151 typedef struct
152 {
153     int             i_waiting_threads;
154     HANDLE          signal;
155 } vlc_cond_t;
156
157 typedef unsigned (__stdcall *PTHREAD_START) (void *);
158
159 #endif
160
161 typedef void *(*vlc_thread_func_t)(void *p_data);
162
163 /*****************************************************************************
164  * Prototypes
165  *****************************************************************************/
166
167 #ifdef GPROF
168 /* Wrapper function for profiling */
169 static void *      vlc_thread_wrapper ( void *p_wrapper );
170
171 #   ifdef WIN32
172
173 #       define ITIMER_REAL 1
174 #       define ITIMER_PROF 2
175
176 struct itimerval
177 {
178     struct timeval it_value;
179     struct timeval it_interval;
180 };
181
182 int setitimer(int kind, const struct itimerval* itnew, struct itimerval* itold);
183
184 #   endif /* WIN32 */
185
186 typedef struct wrapper_s
187 {
188     /* Data lock access */
189     vlc_mutex_t lock;
190     vlc_cond_t  wait;
191
192     /* Data used to spawn the real thread */
193     vlc_thread_func_t func;
194     void *p_data;
195
196     /* Profiling timer passed to the thread */
197     struct itimerval itimer;
198
199 } wrapper_t;
200
201 #endif /* GPROF */
202
203 /*****************************************************************************
204  * vlc_threads_init: initialize threads system
205  *****************************************************************************/
206 static __inline__ int vlc_threads_init( void )
207 {
208 #if defined( PTH_INIT_IN_PTH_H )
209     return pth_init();
210
211 #elif defined( ST_INIT_IN_ST_H )
212     return st_init();
213
214 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
215     return 0;
216
217 #elif defined( HAVE_CTHREADS_H )
218     return 0;
219
220 #elif defined( HAVE_KERNEL_SCHEDULER_H )
221     return 0;
222
223 #elif defined( WIN32 )
224     return 0;
225
226 #endif
227 }
228
229 /*****************************************************************************
230  * vlc_threads_end: stop threads system
231  *****************************************************************************/
232 static __inline__ int vlc_threads_end( void )
233 {
234 #if defined( PTH_INIT_IN_PTH_H )
235     return pth_kill();
236
237 #elif defined( ST_INIT_IN_ST_H )
238     return 0;
239
240 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
241     return 0;
242
243 #elif defined( HAVE_CTHREADS_H )
244     return 0;
245
246 #elif defined( HAVE_KERNEL_SCHEDULER_H )
247     return 0;
248
249 #elif defined( WIN32 )
250     return 0;
251
252 #endif
253 }
254
255 /*****************************************************************************
256  * vlc_mutex_init: initialize a mutex
257  *****************************************************************************/
258 static __inline__ int vlc_mutex_init( vlc_mutex_t *p_mutex )
259 {
260 #if defined( PTH_INIT_IN_PTH_H )
261     return pth_mutex_init( p_mutex );
262
263 #elif defined( ST_INIT_IN_ST_H )
264     *p_mutex = st_mutex_new();
265     return ( *p_mutex == NULL ) ? errno : 0;
266
267 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
268 #   if defined(DEBUG) && defined(SYS_LINUX)
269     /* Create error-checking mutex to detect threads problems more easily. */
270     pthread_mutexattr_t attr;
271     int                 i_result;
272
273     pthread_mutexattr_init( &attr );
274     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
275     i_result = pthread_mutex_init( p_mutex, &attr );
276     pthread_mutexattr_destroy( &attr );
277     return( i_result );
278 #   endif
279
280     return pthread_mutex_init( p_mutex, NULL );
281
282 #elif defined( HAVE_CTHREADS_H )
283     mutex_init( p_mutex );
284     return 0;
285
286 #elif defined( HAVE_KERNEL_SCHEDULER_H )
287
288     /* check the arguments and whether it's already been initialized */
289     if( p_mutex == NULL )
290     {
291         return B_BAD_VALUE;
292     }
293
294     if( p_mutex->init == 9999 )
295     {
296         return EALREADY;
297     }
298
299     p_mutex->lock = create_sem( 1, "BeMutex" );
300     if( p_mutex->lock < B_NO_ERROR )
301     {
302         return( -1 );
303     }
304
305     p_mutex->init = 9999;
306     return B_OK;
307
308 #elif defined( WIN32 )
309     InitializeCriticalSection( p_mutex );
310     return 0;
311
312 #endif
313 }
314
315 /*****************************************************************************
316  * vlc_mutex_lock: lock a mutex
317  *****************************************************************************/
318 #ifdef DEBUG
319 #   define vlc_mutex_lock( P_MUTEX )                                        \
320         _vlc_mutex_lock( __FILE__, __LINE__, P_MUTEX )
321 #else
322 #   define vlc_mutex_lock( P_MUTEX )                                        \
323         _vlc_mutex_lock( NULL, 0, P_MUTEX )
324 #endif
325
326 static __inline__ int _vlc_mutex_lock( char * psz_file, int i_line,
327                                        vlc_mutex_t *p_mutex )
328 {
329 #if defined( PTH_INIT_IN_PTH_H )
330     return pth_mutex_acquire( p_mutex, TRUE, NULL );
331
332 #elif defined( ST_INIT_IN_ST_H )
333     return st_mutex_lock( *p_mutex );
334
335 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
336     int i_return = pthread_mutex_lock( p_mutex );
337     if( i_return )
338     {
339         intf_ErrMsg( "thread %d error: mutex_lock failed at %s:%d (%s)",
340                      pthread_self(), psz_file, i_line, strerror(i_return) );
341     }
342     return i_return;
343
344 #elif defined( HAVE_CTHREADS_H )
345     mutex_lock( p_mutex );
346     return 0;
347
348 #elif defined( HAVE_KERNEL_SCHEDULER_H )
349     status_t err;
350
351     if( !p_mutex )
352     {
353         return B_BAD_VALUE;
354     }
355
356     if( p_mutex->init < 2000 )
357     {
358         return B_NO_INIT;
359     }
360
361     err = acquire_sem( p_mutex->lock );
362     return err;
363
364 #elif defined( WIN32 )
365     EnterCriticalSection( p_mutex );
366     return 0;
367
368 #endif
369 }
370
371 /*****************************************************************************
372  * vlc_mutex_unlock: unlock a mutex
373  *****************************************************************************/
374 #ifdef DEBUG
375 #   define vlc_mutex_unlock( P_MUTEX )                                      \
376         _vlc_mutex_unlock( __FILE__, __LINE__, P_MUTEX )
377 #else
378 #   define vlc_mutex_unlock( P_MUTEX )                                      \
379         _vlc_mutex_unlock( NULL, 0, P_MUTEX )
380 #endif
381
382 static __inline__ int _vlc_mutex_unlock( char * psz_file, int i_line,
383                                          vlc_mutex_t *p_mutex )
384 {
385 #if defined( PTH_INIT_IN_PTH_H )
386     return pth_mutex_release( p_mutex );
387
388 #elif defined( ST_INIT_IN_ST_H )
389     return st_mutex_unlock( *p_mutex );
390
391 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
392     int i_return = pthread_mutex_unlock( p_mutex );
393     if( i_return )
394     {
395         intf_ErrMsg( "thread %d error: mutex_unlock failed at %s:%d (%s)",
396                      pthread_self(), psz_file, i_line, strerror(i_return) );
397     }
398     return i_return;
399
400 #elif defined( HAVE_CTHREADS_H )
401     mutex_unlock( p_mutex );
402     return 0;
403
404 #elif defined( HAVE_KERNEL_SCHEDULER_H )
405     if( !p_mutex)
406     {
407         return B_BAD_VALUE;
408     }
409
410     if( p_mutex->init < 2000 )
411     {
412         return B_NO_INIT;
413     }
414
415     release_sem( p_mutex->lock );
416     return B_OK;
417
418 #elif defined( WIN32 )
419     LeaveCriticalSection( p_mutex );
420     return 0;
421
422 #endif
423 }
424
425 /*****************************************************************************
426  * vlc_mutex_destroy: destroy a mutex
427  *****************************************************************************/
428 #ifdef DEBUG
429 #   define vlc_mutex_destroy( P_MUTEX )                                     \
430         _vlc_mutex_destroy( __FILE__, __LINE__, P_MUTEX )
431 #else
432 #   define vlc_mutex_destroy( P_MUTEX )                                     \
433         _vlc_mutex_destroy( NULL, 0, P_MUTEX )
434 #endif
435
436 static __inline__ int _vlc_mutex_destroy( char * psz_file, int i_line,
437                                           vlc_mutex_t *p_mutex )
438 {
439 #if defined( PTH_INIT_IN_PTH_H )
440     return 0;
441
442 #elif defined( ST_INIT_IN_ST_H )
443     return st_mutex_destroy( *p_mutex );
444
445 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )    
446     int i_return = pthread_mutex_destroy( p_mutex );
447     if( i_return )
448     {
449         intf_ErrMsg( "thread %d error: mutex_destroy failed at %s:%d (%s)",
450                      pthread_self(), psz_file, i_line, strerror(i_return) );
451     }
452     return i_return;
453
454 #elif defined( HAVE_CTHREADS_H )
455     return 0;
456
457 #elif defined( HAVE_KERNEL_SCHEDULER_H )
458     if( p_mutex->init == 9999 )
459     {
460         delete_sem( p_mutex->lock );
461     }
462
463     p_mutex->init = 0;
464     return B_OK;
465
466 #elif defined( WIN32 )
467     DeleteCriticalSection( p_mutex );
468     return 0;
469
470 #endif    
471 }
472
473 /*****************************************************************************
474  * vlc_cond_init: initialize a condition
475  *****************************************************************************/
476 static __inline__ int vlc_cond_init( vlc_cond_t *p_condvar )
477 {
478 #if defined( PTH_INIT_IN_PTH_H )
479     return pth_cond_init( p_condvar );
480
481 #elif defined( ST_INIT_IN_ST_H )
482     *p_condvar = st_cond_new();
483     return ( *p_condvar == NULL ) ? errno : 0;
484
485 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
486     return pthread_cond_init( p_condvar, NULL );
487
488 #elif defined( HAVE_CTHREADS_H )
489     /* condition_init() */
490     spin_lock_init( &p_condvar->lock );
491     cthread_queue_init( &p_condvar->queue );
492     p_condvar->name = 0;
493     p_condvar->implications = 0;
494
495     return 0;
496
497 #elif defined( HAVE_KERNEL_SCHEDULER_H )
498     if( !p_condvar )
499     {
500         return B_BAD_VALUE;
501     }
502
503     if( p_condvar->init == 9999 )
504     {
505         return EALREADY;
506     }
507
508     p_condvar->thread = -1;
509     p_condvar->init = 9999;
510     return 0;
511
512 #elif defined( WIN32 )
513     /* initialise counter */
514     p_condvar->i_waiting_threads = 0;
515
516     /* Create an auto-reset event. */
517     p_condvar->signal = CreateEvent( NULL, /* no security */
518                                      FALSE,  /* auto-reset event */
519                                      FALSE,  /* non-signaled initially */
520                                      NULL ); /* unnamed */
521
522     return( !p_condvar->signal );
523     
524 #endif
525 }
526
527 /*****************************************************************************
528  * vlc_cond_signal: start a thread on condition completion
529  *****************************************************************************/
530 static __inline__ int vlc_cond_signal( vlc_cond_t *p_condvar )
531 {
532 #if defined( PTH_INIT_IN_PTH_H )
533     return pth_cond_notify( p_condvar, FALSE );
534
535 #elif defined( ST_INIT_IN_ST_H )
536     return st_cond_signal( *p_condvar );
537
538 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
539     return pthread_cond_signal( p_condvar );
540
541 #elif defined( HAVE_CTHREADS_H )
542     /* condition_signal() */
543     if ( p_condvar->queue.head || p_condvar->implications )
544     {
545         cond_signal( (condition_t)p_condvar );
546     }
547     return 0;
548
549 #elif defined( HAVE_KERNEL_SCHEDULER_H )
550     if( !p_condvar )
551     {
552         return B_BAD_VALUE;
553     }
554
555     if( p_condvar->init < 2000 )
556     {
557         return B_NO_INIT;
558     }
559
560     while( p_condvar->thread != -1 )
561     {
562         thread_info info;
563         if( get_thread_info(p_condvar->thread, &info) == B_BAD_VALUE )
564         {
565             return 0;
566         }
567
568         if( info.state != B_THREAD_SUSPENDED )
569         {
570             /* The  waiting thread is not suspended so it could
571              * have been interrupted beetwen the unlock and the
572              * suspend_thread line. That is why we sleep a little
573              * before retesting p_condver->thread. */
574             snooze( 10000 );
575         }
576         else
577         {
578             /* Ok, we have to wake up that thread */
579             resume_thread( p_condvar->thread );
580             return 0;
581         }
582     }
583     return 0;
584
585 #elif defined( WIN32 )
586     /* Release one waiting thread if one is available. */
587     /* For this trick to work properly, the vlc_cond_signal must be surrounded
588      * by a mutex. This will prevent another thread from stealing the signal */
589     int i_waiting_threads = p_condvar->i_waiting_threads;
590     while( p_condvar->i_waiting_threads
591            && p_condvar->i_waiting_threads == i_waiting_threads )
592     {
593         PulseEvent( p_condvar->signal );
594         Sleep( 0 ); /* deschedule the current thread */
595     }
596     return 0;
597
598 #endif
599 }
600
601 /*****************************************************************************
602  * vlc_cond_broadcast: start all threads waiting on condition completion
603  *****************************************************************************/
604 /*
605  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
606  * Only works with pthreads, you need to adapt it for others
607  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
608  */
609 static __inline__ int vlc_cond_broadcast( vlc_cond_t *p_condvar )
610 {
611 #if defined( PTH_INIT_IN_PTH_H )
612     return pth_cond_notify( p_condvar, FALSE );
613
614 #elif defined( ST_INIT_IN_ST_H )
615     return st_cond_broadcast( p_condvar );
616
617 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
618     return pthread_cond_broadcast( p_condvar );
619
620 #elif defined( HAVE_CTHREADS_H )
621     /* condition_signal() */
622     if ( p_condvar->queue.head || p_condvar->implications )
623     {
624         cond_signal( (condition_t)p_condvar );
625     }
626     return 0;
627
628 #elif defined( HAVE_KERNEL_SCHEDULER_H )
629     if( !p_condvar )
630     {
631         return B_BAD_VALUE;
632     }
633
634     if( p_condvar->init < 2000 )
635     {
636         return B_NO_INIT;
637     }
638
639     while( p_condvar->thread != -1 )
640     {
641         thread_info info;
642         if( get_thread_info(p_condvar->thread, &info) == B_BAD_VALUE )
643         {
644             return 0;
645         }
646
647         if( info.state != B_THREAD_SUSPENDED )
648         {
649             /* The  waiting thread is not suspended so it could
650              * have been interrupted beetwen the unlock and the
651              * suspend_thread line. That is why we sleep a little
652              * before retesting p_condver->thread. */
653             snooze( 10000 );
654         }
655         else
656         {
657             /* Ok, we have to wake up that thread */
658             resume_thread( p_condvar->thread );
659             return 0;
660         }
661     }
662     return 0;
663
664 #elif defined( WIN32 )
665     /* Release all waiting threads. */
666     /* For this trick to work properly, the vlc_cond_signal must be surrounded
667      * by a mutex. This will prevent another thread from stealing the signal */
668     while( p_condvar->i_waiting_threads )
669     {
670         PulseEvent( p_condvar->signal );
671         Sleep( 0 ); /* deschedule the current thread */
672     }
673     return 0;
674
675 #endif
676 }
677
678 /*****************************************************************************
679  * vlc_cond_wait: wait until condition completion
680  *****************************************************************************/
681 #ifdef DEBUG
682 #   define vlc_cond_wait( P_COND, P_MUTEX )                                 \
683         _vlc_cond_wait( __FILE__, __LINE__, P_COND, P_MUTEX  )
684 #else
685 #   define vlc_cond_wait( P_COND, P_MUTEX )                                 \
686         _vlc_cond_wait( NULL, 0, P_COND, P_MUTEX )
687 #endif
688
689 static __inline__ int _vlc_cond_wait( char * psz_file, int i_line,
690                                       vlc_cond_t *p_condvar,
691                                       vlc_mutex_t *p_mutex )
692 {
693 #if defined( PTH_INIT_IN_PTH_H )
694     return pth_cond_await( p_condvar, p_mutex, NULL );
695
696 #elif defined( ST_INIT_IN_ST_H )
697     int i_ret;
698
699     st_mutex_unlock( *p_mutex );
700     i_ret = st_cond_wait( *p_condvar );
701     st_mutex_lock( *p_mutex );
702
703     return i_ret;
704
705 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
706
707 #ifndef DEBUG
708     return pthread_cond_wait( p_condvar, p_mutex );
709 #else
710     /* In debug mode, timeout */
711     struct timeval now;
712     struct timespec timeout;
713     int    i_result;
714
715     for( ; ; )
716     {
717         gettimeofday( &now, NULL );
718         timeout.tv_sec = now.tv_sec + THREAD_COND_TIMEOUT;
719         timeout.tv_nsec = now.tv_usec * 1000;
720
721         if( (i_result = pthread_cond_timedwait( p_condvar, p_mutex, &timeout )) )
722         {
723             intf_WarnMsg( 1, "thread %d warning: Possible deadlock detected in cond_wait at %s:%d (%s)",
724                           pthread_self(), psz_file, i_line, strerror(i_result) );
725         }
726         else
727         {
728             return i_result;
729         }
730     }
731 #endif
732
733 #elif defined( HAVE_CTHREADS_H )
734     condition_wait( (condition_t)p_condvar, (mutex_t)p_mutex );
735     return 0;
736
737 #elif defined( HAVE_KERNEL_SCHEDULER_H )
738     if( !p_condvar )
739     {
740         return B_BAD_VALUE;
741     }
742
743     if( !p_mutex )
744     {
745         return B_BAD_VALUE;
746     }
747
748     if( p_condvar->init < 2000 )
749     {
750         return B_NO_INIT;
751     }
752
753     /* The p_condvar->thread var is initialized before the unlock because
754      * it enables to identify when the thread is interrupted beetwen the
755      * unlock line and the suspend_thread line */
756     p_condvar->thread = find_thread( NULL );
757     vlc_mutex_unlock( p_mutex );
758     suspend_thread( p_condvar->thread );
759     p_condvar->thread = -1;
760
761     vlc_mutex_lock( p_mutex );
762     return 0;
763
764 #elif defined( WIN32 )
765     /* The ideal would be to use a function which atomically releases the
766      * mutex and initiate the waiting.
767      * Unfortunately only the SignalObjectAndWait function does this and it's
768      * only supported on WinNT/2K, furthermore it cannot take multiple
769      * events as parameters.
770      *
771      * The solution we use should however fulfill all our needs (even though
772      * it is not a correct pthreads implementation)
773      */
774     int i_result;
775
776     p_condvar->i_waiting_threads ++;
777
778     /* Release the mutex */
779     vlc_mutex_unlock( p_mutex );
780
781     i_result = WaitForSingleObject( p_condvar->signal, INFINITE); 
782
783     /* maybe we should protect this with a mutex ? */
784     p_condvar->i_waiting_threads --;
785
786     /* Reacquire the mutex before returning. */
787     vlc_mutex_lock( p_mutex );
788
789     return( i_result == WAIT_FAILED );
790
791 #endif
792 }
793
794 /*****************************************************************************
795  * vlc_cond_destroy: destroy a condition
796  *****************************************************************************/
797 #ifdef DEBUG
798 #   define vlc_cond_destroy( P_COND )                                       \
799         _vlc_cond_destroy( __FILE__, __LINE__, P_COND )
800 #else
801 #   define vlc_cond_destroy( P_COND )                                       \
802         _vlc_cond_destroy( NULL, 0, P_COND )
803 #endif
804
805 static __inline__ int _vlc_cond_destroy( char * psz_file, int i_line,
806                                          vlc_cond_t *p_condvar )
807 {
808 #if defined( PTH_INIT_IN_PTH_H )
809     return 0;
810
811 #elif defined( ST_INIT_IN_ST_H )
812     return st_cond_destroy( *p_condvar );
813
814 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
815     int i_result = pthread_cond_destroy( p_condvar );
816     if( i_result )
817     {
818         intf_ErrMsg( "thread %d error: cond_destroy failed at %s:%d (%s)",
819                      pthread_self(), psz_file, i_line, strerror(i_result) );
820     }
821     return i_result;
822
823 #elif defined( HAVE_CTHREADS_H )
824     return 0;
825
826 #elif defined( HAVE_KERNEL_SCHEDULER_H )
827     p_condvar->init = 0;
828     return 0;
829
830 #elif defined( WIN32 )
831     return( !CloseHandle( p_condvar->signal ) );
832
833 #endif    
834 }
835
836 /*****************************************************************************
837  * vlc_thread_create: create a thread
838  *****************************************************************************/
839 #ifdef DEBUG
840 #   define vlc_thread_create( P_THREAD, PSZ_NAME, FUNC, P_DATA )            \
841         _vlc_thread_create( __FILE__, __LINE__, P_THREAD, PSZ_NAME, FUNC, P_DATA )
842 #else
843 #   define vlc_thread_create( P_THREAD, PSZ_NAME, FUNC, P_DATA )            \
844         _vlc_thread_create( NULL, 0, P_THREAD, PSZ_NAME, FUNC, P_DATA )
845 #endif
846
847 static __inline__ int _vlc_thread_create( char * psz_file, int i_line,
848                                           vlc_thread_t *p_thread,
849                                           char *psz_name,
850                                           vlc_thread_func_t func,
851                                           void *p_data )
852 {
853     int i_ret;
854
855 #ifdef GPROF
856     wrapper_t wrapper;
857
858     /* Initialize the wrapper structure */
859     wrapper.func = func;
860     wrapper.p_data = p_data;
861     getitimer( ITIMER_PROF, &wrapper.itimer );
862     vlc_mutex_init( &wrapper.lock );
863     vlc_cond_init( &wrapper.wait );
864     vlc_mutex_lock( &wrapper.lock );
865
866     /* Alter user-passed data so that we call the wrapper instead
867      * of the real function */
868     p_data = &wrapper;
869     func = vlc_thread_wrapper;
870 #endif
871
872 #if defined( PTH_INIT_IN_PTH_H )
873     *p_thread = pth_spawn( PTH_ATTR_DEFAULT, func, p_data );
874     i_ret = ( p_thread == NULL );
875
876 #elif defined( ST_INIT_IN_ST_H )
877     *p_thread = st_thread_create( func, p_data, 1, 0 );
878     i_ret = ( p_thread == NULL );
879     
880 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
881     i_ret = pthread_create( p_thread, NULL, func, p_data );
882
883 #elif defined( HAVE_CTHREADS_H )
884     *p_thread = cthread_fork( (cthread_fn_t)func, (any_t)p_data );
885     i_ret = 0;
886
887 #elif defined( HAVE_KERNEL_SCHEDULER_H )
888     *p_thread = spawn_thread( (thread_func)func, psz_name,
889                               B_NORMAL_PRIORITY, p_data );
890     i_ret = resume_thread( *p_thread );
891
892 #elif defined( WIN32 )
893 #if 0
894     DWORD threadID;
895     /* This method is not recommended when using the MSVCRT C library,
896      * so we'll have to use _beginthreadex instead */
897     *p_thread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE) func, 
898                              p_data, 0, &threadID);
899 #endif
900     unsigned threadID;
901     /* When using the MSVCRT C library you have to use the _beginthreadex
902      * function instead of CreateThread, otherwise you'll end up with memory
903      * leaks and the signal function not working */
904     *p_thread = (HANDLE)_beginthreadex(NULL, 0, (PTHREAD_START) func, 
905                              p_data, 0, &threadID);
906     
907     i_ret = ( *p_thread ? 0 : 1 );
908
909 #endif
910
911 #ifdef GPROF
912     if( i_ret == 0 )
913     {
914         vlc_cond_wait( &wrapper.wait, &wrapper.lock );
915     }
916
917     vlc_mutex_unlock( &wrapper.lock );
918     vlc_mutex_destroy( &wrapper.lock );
919     vlc_cond_destroy( &wrapper.wait );
920 #endif
921
922     if( i_ret == 0 )
923     {
924         intf_WarnMsg( 2, "thread info: %d (%s) has been created (%s:%d)",
925                       *p_thread, psz_name, psz_file, i_line );
926     }
927     else
928     {
929         intf_ErrMsg( "thread error: %s couldn't be created at %s:%d (%s)",
930                      psz_name, psz_file, i_line, strerror(i_ret) );
931     }
932
933     return i_ret;
934 }
935
936 /*****************************************************************************
937  * vlc_thread_exit: terminate a thread
938  *****************************************************************************/
939 static __inline__ void vlc_thread_exit( void )
940 {
941 #if defined( PTH_INIT_IN_PTH_H )
942     pth_exit( 0 );
943
944 #elif defined( ST_INIT_IN_ST_H )
945     int result;
946     st_thread_exit( &result );
947     
948 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
949     pthread_exit( 0 );
950
951 #elif defined( HAVE_CTHREADS_H )
952     int result;
953     cthread_exit( &result );
954
955 #elif defined( HAVE_KERNEL_SCHEDULER_H )
956     exit_thread( 0 );
957
958 #elif defined( WIN32 )
959 #if 0
960     ExitThread( 0 );
961 #endif
962     /* For now we don't close the thread handles (because of race conditions).
963      * Need to be looked at. */
964     _endthreadex(0);
965
966 #endif
967 }
968
969 /*****************************************************************************
970  * vlc_thread_join: wait until a thread exits
971  *****************************************************************************/
972 #ifdef DEBUG
973 #   define vlc_thread_join( THREAD )                                        \
974         _vlc_thread_join( __FILE__, __LINE__, THREAD ) 
975 #else
976 #   define vlc_thread_join( THREAD )                                        \
977         _vlc_thread_join( NULL, 0, THREAD ) 
978 #endif
979
980 static __inline__ void _vlc_thread_join( char * psz_file, int i_line,
981                                          vlc_thread_t thread )
982 {
983     int i_ret = 0;
984
985 #if defined( PTH_INIT_IN_PTH_H )
986     i_ret = pth_join( thread, NULL );
987
988 #elif defined( ST_INIT_IN_ST_H )
989     i_ret = st_thread_join( thread, NULL );
990     
991 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
992     i_ret = pthread_join( thread, NULL );
993
994 #elif defined( HAVE_CTHREADS_H )
995     cthread_join( thread );
996     i_ret = 1;
997
998 #elif defined( HAVE_KERNEL_SCHEDULER_H )
999     int32 exit_value;
1000     wait_for_thread( thread, &exit_value );
1001
1002 #elif defined( WIN32 )
1003     WaitForSingleObject( thread, INFINITE );
1004
1005 #endif
1006
1007     if( i_ret )
1008     {
1009         intf_ErrMsg( "thread error: thread_join(%d) failed at %s:%d (%s)",
1010                      thread, psz_file, i_line, strerror(i_ret) );
1011     }
1012     else
1013     {
1014         intf_WarnMsg( 2, "thread info: %d has been joined (%s:%d)",
1015                       thread, psz_file, i_line );
1016     }
1017 }
1018
1019 #ifdef GPROF
1020 static void *vlc_thread_wrapper( void *p_wrapper )
1021 {
1022     /* Put user data in thread-local variables */
1023     void *            p_data = ((wrapper_t*)p_wrapper)->p_data;
1024     vlc_thread_func_t func   = ((wrapper_t*)p_wrapper)->func;
1025
1026     /* Set the profile timer value */
1027     setitimer( ITIMER_PROF, &((wrapper_t*)p_wrapper)->itimer, NULL );
1028
1029     /* Tell the calling thread that we don't need its data anymore */
1030     vlc_mutex_lock( &((wrapper_t*)p_wrapper)->lock );
1031     vlc_cond_signal( &((wrapper_t*)p_wrapper)->wait );
1032     vlc_mutex_unlock( &((wrapper_t*)p_wrapper)->lock );
1033
1034     /* Call the real function */
1035     return func( p_data );
1036 }
1037 #endif
1038