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