]> git.sesse.net Git - vlc/blob - include/threads.h
* ./include/threads.h: fixed a segfault under Solaris, thanks to Meuuh.
[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.41 2002/04/18 12:51:59 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( WIN32 )
39 #   include <process.h>
40
41 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )  /* pthreads (like Linux & BSD) */
42 #   include <pthread.h>
43 #   ifdef DEBUG
44 /* Needed for pthread_cond_timedwait */
45 #       include <errno.h>
46 #   endif
47 /* This is not prototyped under Linux, though it exists. */
48 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
49
50 #elif defined( HAVE_CTHREADS_H )                                  /* GNUMach */
51 #   include <cthreads.h>
52
53 #elif defined( HAVE_KERNEL_SCHEDULER_H )                             /* BeOS */
54 #   include <kernel/OS.h>
55 #   include <kernel/scheduler.h>
56 #   include <byteorder.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( WIN32 )
104 typedef HANDLE vlc_thread_t;
105
106 typedef struct
107 {
108     CRITICAL_SECTION csection;
109     HANDLE           mutex;
110 } vlc_mutex_t;
111
112 typedef struct
113 {
114     int             i_waiting_threads;
115     HANDLE          signal;
116 } vlc_cond_t;
117
118 typedef unsigned (__stdcall *PTHREAD_START) (void *);
119
120 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
121 typedef pthread_t        vlc_thread_t;
122 typedef pthread_mutex_t  vlc_mutex_t;
123 typedef pthread_cond_t   vlc_cond_t;
124
125 #elif defined( HAVE_CTHREADS_H )
126 typedef cthread_t        vlc_thread_t;
127
128 /* Those structs are the ones defined in /include/cthreads.h but we need
129  * to handle (*foo) where foo is a (mutex_t) while they handle (foo) where
130  * foo is a (mutex_t*) */
131 typedef struct s_mutex {
132     spin_lock_t held;
133     spin_lock_t lock;
134     char *name;
135     struct cthread_queue queue;
136 } vlc_mutex_t;
137
138 typedef struct s_condition {
139     spin_lock_t lock;
140     struct cthread_queue queue;
141     char *name;
142     struct cond_imp *implications;
143 } vlc_cond_t;
144
145 #elif defined( HAVE_KERNEL_SCHEDULER_H )
146 /* This is the BeOS implementation of the vlc threads, note that the mutex is
147  * not a real mutex and the cond_var is not like a pthread cond_var but it is
148  * enough for what wee need */
149
150 typedef thread_id vlc_thread_t;
151
152 typedef struct
153 {
154     int32           init;
155     sem_id          lock;
156 } vlc_mutex_t;
157
158 typedef struct
159 {
160     int32           init;
161     thread_id       thread;
162 } vlc_cond_t;
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( WIN32 )
220     return 0;
221
222 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
223     return 0;
224
225 #elif defined( HAVE_CTHREADS_H )
226     return 0;
227
228 #elif defined( HAVE_KERNEL_SCHEDULER_H )
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( WIN32 )
246     return 0;
247
248 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
249     return 0;
250
251 #elif defined( HAVE_CTHREADS_H )
252     return 0;
253
254 #elif defined( HAVE_KERNEL_SCHEDULER_H )
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( WIN32 )
273     /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
274      * function and have a 100% correct vlc_cond_wait() implementation.
275      * As this function is not available on Win9x, we can use the faster
276      * CriticalSections */
277     if( (GetVersion() < 0x80000000) && !p_main_sys->b_fast_pthread )
278     {
279         /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
280         p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
281         return ( p_mutex->mutex ? 0 : 1 );
282     }
283     else
284     {
285         InitializeCriticalSection( &p_mutex->csection );
286         p_mutex->mutex = NULL;
287         return 0;
288     }
289
290 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
291 #   if defined(DEBUG) && defined(SYS_LINUX)
292     /* Create error-checking mutex to detect threads problems more easily. */
293     pthread_mutexattr_t attr;
294     int                 i_result;
295
296     pthread_mutexattr_init( &attr );
297     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
298     i_result = pthread_mutex_init( p_mutex, &attr );
299     pthread_mutexattr_destroy( &attr );
300     return( i_result );
301 #   endif
302
303     return pthread_mutex_init( p_mutex, NULL );
304
305 #elif defined( HAVE_CTHREADS_H )
306     mutex_init( p_mutex );
307     return 0;
308
309 #elif defined( HAVE_KERNEL_SCHEDULER_H )
310
311     /* check the arguments and whether it's already been initialized */
312     if( p_mutex == NULL )
313     {
314         return B_BAD_VALUE;
315     }
316
317     if( p_mutex->init == 9999 )
318     {
319         return EALREADY;
320     }
321
322     p_mutex->lock = create_sem( 1, "BeMutex" );
323     if( p_mutex->lock < B_NO_ERROR )
324     {
325         return( -1 );
326     }
327
328     p_mutex->init = 9999;
329     return B_OK;
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( "(unknown)", 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( WIN32 )
355     if( p_mutex->mutex )
356     {
357         WaitForSingleObject( p_mutex->mutex, INFINITE );
358     }
359     else
360     {
361         EnterCriticalSection( &p_mutex->csection );
362     }
363     return 0;
364
365 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
366     int i_return = pthread_mutex_lock( p_mutex );
367     if( i_return )
368     {
369         intf_ErrMsg( "thread %d error: mutex_lock failed at %s:%d (%s)",
370                      pthread_self(), psz_file, i_line, strerror(i_return) );
371     }
372     return i_return;
373
374 #elif defined( HAVE_CTHREADS_H )
375     mutex_lock( p_mutex );
376     return 0;
377
378 #elif defined( HAVE_KERNEL_SCHEDULER_H )
379     status_t err;
380
381     if( !p_mutex )
382     {
383         return B_BAD_VALUE;
384     }
385
386     if( p_mutex->init < 2000 )
387     {
388         return B_NO_INIT;
389     }
390
391     err = acquire_sem( p_mutex->lock );
392     return err;
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( "(unknown)", 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( WIN32 )
418     if( p_mutex->mutex )
419     {
420         ReleaseMutex( p_mutex->mutex );
421     }
422     else
423     {
424         LeaveCriticalSection( &p_mutex->csection );
425     }
426     return 0;
427
428 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
429     int i_return = pthread_mutex_unlock( p_mutex );
430     if( i_return )
431     {
432         intf_ErrMsg( "thread %d error: mutex_unlock failed at %s:%d (%s)",
433                      pthread_self(), psz_file, i_line, strerror(i_return) );
434     }
435     return i_return;
436
437 #elif defined( HAVE_CTHREADS_H )
438     mutex_unlock( p_mutex );
439     return 0;
440
441 #elif defined( HAVE_KERNEL_SCHEDULER_H )
442     if( !p_mutex)
443     {
444         return B_BAD_VALUE;
445     }
446
447     if( p_mutex->init < 2000 )
448     {
449         return B_NO_INIT;
450     }
451
452     release_sem( p_mutex->lock );
453     return B_OK;
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( "(unknown)", 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( WIN32 )
479     if( p_mutex->mutex )
480     {
481         CloseHandle( p_mutex->mutex );
482     }
483     else
484     {
485         DeleteCriticalSection( &p_mutex->csection );
486     }
487     return 0;
488
489 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )    
490     int i_return = pthread_mutex_destroy( p_mutex );
491     if( i_return )
492     {
493         intf_ErrMsg( "thread %d error: mutex_destroy failed at %s:%d (%s)",
494                      pthread_self(), psz_file, i_line, strerror(i_return) );
495     }
496     return i_return;
497
498 #elif defined( HAVE_CTHREADS_H )
499     return 0;
500
501 #elif defined( HAVE_KERNEL_SCHEDULER_H )
502     if( p_mutex->init == 9999 )
503     {
504         delete_sem( p_mutex->lock );
505     }
506
507     p_mutex->init = 0;
508     return B_OK;
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( WIN32 )
526     /* initialise counter */
527     p_condvar->i_waiting_threads = 0;
528
529     /* Create an auto-reset event. */
530     p_condvar->signal = CreateEvent( NULL, /* no security */
531                                      FALSE,  /* auto-reset event */
532                                      FALSE,  /* non-signaled initially */
533                                      NULL ); /* unnamed */
534
535     return( !p_condvar->signal );
536
537 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
538     return pthread_cond_init( p_condvar, NULL );
539
540 #elif defined( HAVE_CTHREADS_H )
541     /* condition_init() */
542     spin_lock_init( &p_condvar->lock );
543     cthread_queue_init( &p_condvar->queue );
544     p_condvar->name = 0;
545     p_condvar->implications = 0;
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 == 9999 )
556     {
557         return EALREADY;
558     }
559
560     p_condvar->thread = -1;
561     p_condvar->init = 9999;
562     return 0;
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( WIN32 )
579     /* Release one waiting thread if one is available. */
580     /* For this trick to work properly, the vlc_cond_signal must be surrounded
581      * by a mutex. This will prevent another thread from stealing the signal */
582     PulseEvent( p_condvar->signal );
583     return 0;
584
585 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
586     return pthread_cond_signal( p_condvar );
587
588 #elif defined( HAVE_CTHREADS_H )
589     /* condition_signal() */
590     if ( p_condvar->queue.head || p_condvar->implications )
591     {
592         cond_signal( (condition_t)p_condvar );
593     }
594     return 0;
595
596 #elif defined( HAVE_KERNEL_SCHEDULER_H )
597     if( !p_condvar )
598     {
599         return B_BAD_VALUE;
600     }
601
602     if( p_condvar->init < 2000 )
603     {
604         return B_NO_INIT;
605     }
606
607     while( p_condvar->thread != -1 )
608     {
609         thread_info info;
610         if( get_thread_info(p_condvar->thread, &info) == B_BAD_VALUE )
611         {
612             return 0;
613         }
614
615         if( info.state != B_THREAD_SUSPENDED )
616         {
617             /* The  waiting thread is not suspended so it could
618              * have been interrupted beetwen the unlock and the
619              * suspend_thread line. That is why we sleep a little
620              * before retesting p_condver->thread. */
621             snooze( 10000 );
622         }
623         else
624         {
625             /* Ok, we have to wake up that thread */
626             resume_thread( p_condvar->thread );
627             return 0;
628         }
629     }
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( WIN32 )
652     /* Release all waiting threads. */
653     /* For this trick to work properly, the vlc_cond_signal must be surrounded
654      * by a mutex. This will prevent another thread from stealing the signal */
655     while( p_condvar->i_waiting_threads )
656     {
657         PulseEvent( p_condvar->signal );
658         Sleep( 1 ); /* deschedule the current thread */
659     }
660     return 0;
661
662 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
663     return pthread_cond_broadcast( p_condvar );
664
665 #elif defined( HAVE_CTHREADS_H )
666     /* condition_signal() */
667     if ( p_condvar->queue.head || p_condvar->implications )
668     {
669         cond_signal( (condition_t)p_condvar );
670     }
671     return 0;
672
673 #elif defined( HAVE_KERNEL_SCHEDULER_H )
674     if( !p_condvar )
675     {
676         return B_BAD_VALUE;
677     }
678
679     if( p_condvar->init < 2000 )
680     {
681         return B_NO_INIT;
682     }
683
684     while( p_condvar->thread != -1 )
685     {
686         thread_info info;
687         if( get_thread_info(p_condvar->thread, &info) == B_BAD_VALUE )
688         {
689             return 0;
690         }
691
692         if( info.state != B_THREAD_SUSPENDED )
693         {
694             /* The  waiting thread is not suspended so it could
695              * have been interrupted beetwen the unlock and the
696              * suspend_thread line. That is why we sleep a little
697              * before retesting p_condver->thread. */
698             snooze( 10000 );
699         }
700         else
701         {
702             /* Ok, we have to wake up that thread */
703             resume_thread( p_condvar->thread );
704             return 0;
705         }
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( "(unknown)", 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( WIN32 )
740     /* The ideal would be to use a function which atomically releases the
741      * mutex and initiate the waiting.
742      * Unfortunately only the SignalObjectAndWait function does this and it's
743      * only supported on WinNT/2K, furthermore it cannot take multiple
744      * events as parameters.
745      *
746      * The solution we use should however fulfill all our needs (even though
747      * it is not a correct pthreads implementation)
748      */
749     int i_result;
750
751     p_condvar->i_waiting_threads ++;
752
753     if( p_mutex->mutex )
754     {
755         p_main_sys->SignalObjectAndWait( p_mutex->mutex, p_condvar->signal,
756                                          INFINITE, FALSE );
757     }
758     else
759     {
760         /* Release the mutex */
761         vlc_mutex_unlock( p_mutex );
762         i_result = WaitForSingleObject( p_condvar->signal, INFINITE); 
763         p_condvar->i_waiting_threads --;
764     }
765
766     /* Reacquire the mutex before returning. */
767     vlc_mutex_lock( p_mutex );
768
769     return( i_result == WAIT_FAILED );
770
771 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
772
773 #ifndef DEBUG
774     return pthread_cond_wait( p_condvar, p_mutex );
775 #else
776     /* In debug mode, timeout */
777     struct timeval now;
778     struct timespec timeout;
779     int    i_result;
780
781     for( ; ; )
782     {
783         gettimeofday( &now, NULL );
784         timeout.tv_sec = now.tv_sec + THREAD_COND_TIMEOUT;
785         timeout.tv_nsec = now.tv_usec * 1000;
786
787         i_result = pthread_cond_timedwait( p_condvar, p_mutex, &timeout );
788
789         if( i_result == ETIMEDOUT )
790         {
791             intf_WarnMsg( 1, "thread %d warning: Possible deadlock detected in cond_wait at %s:%d (%s)",
792                           pthread_self(), psz_file, i_line, strerror(i_result) );
793             continue;
794         }
795
796         if( i_result )
797         {
798             intf_ErrMsg( "thread %d error: cond_wait failed at %s:%d (%s)",
799                          pthread_self(), psz_file, i_line, strerror(i_result) );
800         }
801         return( i_result );
802     }
803 #endif
804
805 #elif defined( HAVE_CTHREADS_H )
806     condition_wait( (condition_t)p_condvar, (mutex_t)p_mutex );
807     return 0;
808
809 #elif defined( HAVE_KERNEL_SCHEDULER_H )
810     if( !p_condvar )
811     {
812         return B_BAD_VALUE;
813     }
814
815     if( !p_mutex )
816     {
817         return B_BAD_VALUE;
818     }
819
820     if( p_condvar->init < 2000 )
821     {
822         return B_NO_INIT;
823     }
824
825     /* The p_condvar->thread var is initialized before the unlock because
826      * it enables to identify when the thread is interrupted beetwen the
827      * unlock line and the suspend_thread line */
828     p_condvar->thread = find_thread( NULL );
829     vlc_mutex_unlock( p_mutex );
830     suspend_thread( p_condvar->thread );
831     p_condvar->thread = -1;
832
833     vlc_mutex_lock( p_mutex );
834     return 0;
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( "(unknown)", 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( WIN32 )
860     return( !CloseHandle( p_condvar->signal ) );
861
862 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
863     int i_result = pthread_cond_destroy( p_condvar );
864     if( i_result )
865     {
866         intf_ErrMsg( "thread %d error: cond_destroy failed at %s:%d (%s)",
867                      pthread_self(), psz_file, i_line, strerror(i_result) );
868     }
869     return i_result;
870
871 #elif defined( HAVE_CTHREADS_H )
872     return 0;
873
874 #elif defined( HAVE_KERNEL_SCHEDULER_H )
875     p_condvar->init = 0;
876     return 0;
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( "(unknown)", 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( WIN32 )
926     unsigned threadID;
927     /* When using the MSVCRT C library you have to use the _beginthreadex
928      * function instead of CreateThread, otherwise you'll end up with memory
929      * leaks and the signal functions not working */
930     *p_thread = (HANDLE)_beginthreadex( NULL, 0, (PTHREAD_START) func, 
931                                         p_data, 0, &threadID );
932     
933     i_ret = ( *p_thread ? 0 : 1 );
934
935 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
936     i_ret = pthread_create( p_thread, NULL, func, p_data );
937
938 #elif defined( HAVE_CTHREADS_H )
939     *p_thread = cthread_fork( (cthread_fn_t)func, (any_t)p_data );
940     i_ret = 0;
941
942 #elif defined( HAVE_KERNEL_SCHEDULER_H )
943     *p_thread = spawn_thread( (thread_func)func, psz_name,
944                               B_NORMAL_PRIORITY, p_data );
945     i_ret = resume_thread( *p_thread );
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( WIN32 )
987     /* For now we don't close the thread handles (because of race conditions).
988      * Need to be looked at. */
989     _endthreadex(0);
990
991 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
992     pthread_exit( 0 );
993
994 #elif defined( HAVE_CTHREADS_H )
995     int result;
996     cthread_exit( &result );
997
998 #elif defined( HAVE_KERNEL_SCHEDULER_H )
999     exit_thread( 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( "(unknown)", 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( WIN32 )
1027     WaitForSingleObject( thread, INFINITE );
1028
1029 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
1030     i_ret = pthread_join( thread, NULL );
1031
1032 #elif defined( HAVE_CTHREADS_H )
1033     cthread_join( thread );
1034     i_ret = 1;
1035
1036 #elif defined( HAVE_KERNEL_SCHEDULER_H )
1037     int32 exit_value;
1038     wait_for_thread( thread, &exit_value );
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