]> git.sesse.net Git - vlc/blob - src/misc/threads.c
* ./bootstrap : Fixed an issue with old shell versions
[vlc] / src / misc / threads.c
1 /*****************************************************************************
2  * threads.c : threads implementation for the VideoLAN client
3  *****************************************************************************
4  * Copyright (C) 1999, 2000, 2001, 2002 VideoLAN
5  * $Id: threads.c,v 1.13 2002/08/29 23:53:22 massiot Exp $
6  *
7  * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          Gildas Bazin <gbazin@netcourrier.com>
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 <vlc/vlc.h>
27
28 #define VLC_THREADS_UNINITIALIZED  0
29 #define VLC_THREADS_PENDING        1
30 #define VLC_THREADS_ERROR          2
31 #define VLC_THREADS_READY          3
32
33 /*****************************************************************************
34  * Prototype for GPROF wrapper
35  *****************************************************************************/
36 #ifdef GPROF
37 /* Wrapper function for profiling */
38 static void *      vlc_thread_wrapper ( void *p_wrapper );
39
40 #   ifdef WIN32
41
42 #       define ITIMER_REAL 1
43 #       define ITIMER_PROF 2
44
45 struct itimerval
46 {
47     struct timeval it_value;
48     struct timeval it_interval;
49 };  
50
51 int setitimer(int kind, const struct itimerval* itnew, struct itimerval* itold);
52 #   endif /* WIN32 */
53
54 typedef struct wrapper_t
55 {
56     /* Data lock access */
57     vlc_mutex_t lock;
58     vlc_cond_t  wait;
59     
60     /* Data used to spawn the real thread */
61     vlc_thread_func_t func;
62     void *p_data;
63     
64     /* Profiling timer passed to the thread */
65     struct itimerval itimer;
66     
67 } wrapper_t;
68
69 #endif /* GPROF */
70
71 /*****************************************************************************
72  * Global mutexes for lazy initialization of the threads system
73  *****************************************************************************/
74 static volatile int i_initializations = 0;
75
76 #if defined( PTH_INIT_IN_PTH_H )
77     /* Unimplemented */
78 #elif defined( ST_INIT_IN_ST_H )
79     /* Unimplemented */
80 #elif defined( WIN32 )
81     /* Unimplemented */
82 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
83     static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
84 #elif defined( HAVE_CTHREADS_H )
85     /* Unimplemented */
86 #elif defined( HAVE_KERNEL_SCHEDULER_H )
87     /* Unimplemented */
88 #endif
89
90 /*****************************************************************************
91  * vlc_threads_init: initialize threads system
92  *****************************************************************************
93  * This function requires lazy initialization of a global lock in order to
94  * keep the library really thread-safe. Some architectures don't support this
95  * and thus do not guarantee the complete reentrancy.
96  *****************************************************************************/
97 int __vlc_threads_init( vlc_object_t *p_this )
98 {
99     static volatile int i_status = VLC_THREADS_UNINITIALIZED;
100     int i_ret = 0;
101
102 #if defined( PTH_INIT_IN_PTH_H )
103     /* Unimplemented */
104 #elif defined( ST_INIT_IN_ST_H )
105     /* Unimplemented */
106 #elif defined( WIN32 )
107     /* Unimplemented */
108 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
109     pthread_mutex_lock( &once_mutex );
110 #elif defined( HAVE_CTHREADS_H )
111     /* Unimplemented */
112 #elif defined( HAVE_KERNEL_SCHEDULER_H )
113     /* Unimplemented */
114 #endif
115
116     if( i_status == VLC_THREADS_UNINITIALIZED )
117     {
118         i_status = VLC_THREADS_PENDING;
119
120 #if defined( PTH_INIT_IN_PTH_H )
121         i_ret = pth_init();
122 #elif defined( ST_INIT_IN_ST_H )
123         i_ret = st_init();
124 #elif defined( WIN32 )
125         /* Unimplemented */
126 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
127         /* Unimplemented */
128 #elif defined( HAVE_CTHREADS_H )
129         /* Unimplemented */
130 #elif defined( HAVE_KERNEL_SCHEDULER_H )
131         /* Unimplemented */
132 #endif
133
134         if( i_ret )
135         {
136             i_status = VLC_THREADS_ERROR;
137         }
138         else
139         {
140             vlc_mutex_init( p_this, p_this->p_vlc->p_global_lock );
141             i_status = VLC_THREADS_READY;
142         }
143     }
144     else
145     {
146         i_ret = ( i_status == VLC_THREADS_READY );
147     }
148
149     i_initializations++;
150
151 #if defined( PTH_INIT_IN_PTH_H )
152     /* Unimplemented */
153 #elif defined( ST_INIT_IN_ST_H )
154     /* Unimplemented */
155 #elif defined( WIN32 )
156     /* Unimplemented */
157 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
158     pthread_mutex_unlock( &once_mutex );
159     return i_ret;
160 #elif defined( HAVE_CTHREADS_H )
161     /* Unimplemented */
162 #elif defined( HAVE_KERNEL_SCHEDULER_H )
163     /* Unimplemented */
164 #endif
165
166     /* Wait until the other thread has initialized the thread library */
167     while( i_status == VLC_THREADS_PENDING )
168     {
169         msleep( THREAD_SLEEP );
170     }
171
172     return i_status == VLC_THREADS_READY;
173 }
174
175 /*****************************************************************************
176  * vlc_threads_end: stop threads system
177  *****************************************************************************
178  * FIXME: This function is far from being threadsafe. We should undo exactly
179  * what we did above in vlc_threads_init.
180  *****************************************************************************/
181 int __vlc_threads_end( vlc_object_t *p_this )
182 {
183 #if defined( PTH_INIT_IN_PTH_H )
184     i_initializations--;
185     if( i_initializations == 0 )
186     {
187         return pth_kill();
188     }
189     return 0;
190
191 #elif defined( ST_INIT_IN_ST_H )
192     i_initializations--;
193     return 0;
194
195 #elif defined( WIN32 )
196     i_initializations--;
197     return 0;
198
199 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
200     pthread_mutex_lock( &once_mutex );
201     i_initializations--;
202     pthread_mutex_unlock( &once_mutex );
203     return 0;
204
205 #elif defined( HAVE_CTHREADS_H )
206     i_initializations--;
207     return 0;
208
209 #elif defined( HAVE_KERNEL_SCHEDULER_H )
210     i_initializations--;
211     return 0;
212
213 #endif
214 }
215
216 /*****************************************************************************
217  * vlc_mutex_init: initialize a mutex
218  *****************************************************************************/
219 int __vlc_mutex_init( vlc_object_t *p_this, vlc_mutex_t *p_mutex )
220 {
221     p_mutex->p_this = p_this;
222
223 #if defined( PTH_INIT_IN_PTH_H )
224     return pth_mutex_init( &p_mutex->mutex );
225
226 #elif defined( ST_INIT_IN_ST_H )
227     *p_mutex->mutex = st_mutex_new();
228     return ( *p_mutex == NULL ) ? errno : 0;
229
230 #elif defined( WIN32 )
231     /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
232      * function and have a 100% correct vlc_cond_wait() implementation.
233      * As this function is not available on Win9x, we can use the faster
234      * CriticalSections */
235     if( p_this->p_vlc->SignalObjectAndWait && !p_this->p_vlc->b_fast_mutex )
236     {
237         /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
238         p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
239         return ( p_mutex->mutex != NULL ? 0 : 1 );
240     }
241     else
242     {
243         p_mutex->mutex = NULL;
244         InitializeCriticalSection( &p_mutex->csection );
245         return 0;
246     }
247
248 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
249 #   if defined(DEBUG) && defined(SYS_LINUX)
250     {
251         /* Create error-checking mutex to detect problems more easily. */
252         pthread_mutexattr_t attr;
253         int                 i_result;
254
255         pthread_mutexattr_init( &attr );
256         pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
257         i_result = pthread_mutex_init( p_mutex, &attr );
258         pthread_mutexattr_destroy( &attr );
259         return( i_result );
260     }
261 #   endif
262     return pthread_mutex_init( &p_mutex->mutex, NULL );
263
264 #elif defined( HAVE_CTHREADS_H )
265     mutex_init( p_mutex );
266     return 0;
267
268 #elif defined( HAVE_KERNEL_SCHEDULER_H )
269     /* check the arguments and whether it's already been initialized */
270     if( p_mutex == NULL )
271     {
272         return B_BAD_VALUE;
273     }
274
275     if( p_mutex->init == 9999 )
276     {
277         return EALREADY;
278     }
279
280     p_mutex->lock = create_sem( 1, "BeMutex" );
281     if( p_mutex->lock < B_NO_ERROR )
282     {
283         return( -1 );
284     }
285
286     p_mutex->init = 9999;
287     return B_OK;
288
289 #endif
290 }
291
292 /*****************************************************************************
293  * vlc_mutex_destroy: destroy a mutex, inner version
294  *****************************************************************************/
295 int __vlc_mutex_destroy( char * psz_file, int i_line, vlc_mutex_t *p_mutex )
296 {
297     int i_result;
298     /* In case of error : */
299     int i_thread = -1;
300     const char * psz_error = "";
301
302 #if defined( PTH_INIT_IN_PTH_H )
303     return 0;
304
305 #elif defined( ST_INIT_IN_ST_H )
306     i_result = st_mutex_destroy( *p_mutex );
307
308 #elif defined( WIN32 )
309     if( p_mutex->mutex )
310     {
311         CloseHandle( p_mutex->mutex );
312     }
313     else
314     {
315         DeleteCriticalSection( &p_mutex->csection );
316     }
317     return 0;
318
319 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )    
320     i_result = pthread_mutex_destroy( &p_mutex->mutex );
321     if ( i_result )
322     {
323         i_thread = pthread_self();
324         psz_error = strerror(i_result);
325     }
326
327 #elif defined( HAVE_CTHREADS_H )
328     return 0;
329
330 #elif defined( HAVE_KERNEL_SCHEDULER_H )
331     if( p_mutex->init == 9999 )
332     {
333         delete_sem( p_mutex->lock );
334     }
335
336     p_mutex->init = 0;
337     return B_OK;
338 #endif    
339
340     if( i_result )
341     {
342         msg_Err( p_mutex->p_this,
343                  "thread %d: mutex_destroy failed at %s:%d (%d:%s)",
344                  i_thread, psz_file, i_line, i_result, psz_error );
345     }
346     return i_result;
347 }
348
349 /*****************************************************************************
350  * vlc_cond_init: initialize a condition
351  *****************************************************************************/
352 int __vlc_cond_init( vlc_object_t *p_this, vlc_cond_t *p_condvar )
353 {
354     p_condvar->p_this = p_this;
355
356 #if defined( PTH_INIT_IN_PTH_H )
357     return pth_cond_init( &p_condvar->cond );
358
359 #elif defined( ST_INIT_IN_ST_H )
360     *p_condvar->cond = st_cond_new();
361     return ( *p_condvar->cond == NULL ) ? errno : 0;
362
363 #elif defined( WIN32 )
364     /* Initialize counter */
365     p_condvar->i_waiting_threads = 0;
366
367     /* Misc init */
368     p_condvar->i_win9x_cv = p_this->p_vlc->i_win9x_cv;
369     p_condvar->SignalObjectAndWait = p_this->p_vlc->SignalObjectAndWait;
370
371     if( p_this->p_vlc->i_win9x_cv == 0 )
372     {
373         /* Create an auto-reset event. */
374         p_condvar->event = CreateEvent( NULL,   /* no security */
375                                         FALSE,  /* auto-reset event */
376                                         FALSE,  /* start non-signaled */
377                                         NULL ); /* unnamed */
378
379         p_condvar->semaphore = NULL;
380         return !p_condvar->event;
381     }
382     else
383     {
384         p_condvar->semaphore = CreateSemaphore( NULL,       /* no security */
385                                                 0,          /* initial count */
386                                                 0x7fffffff, /* max count */
387                                                 NULL );     /* unnamed */
388
389         if( p_this->p_vlc->i_win9x_cv == 1 )
390             /* Create a manual-reset event initially signaled. */
391             p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
392         else
393             /* Create a auto-reset event. */
394             p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
395
396         InitializeCriticalSection( &p_condvar->csection );
397
398         return !p_condvar->semaphore || !p_condvar->event;
399     }
400
401 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
402     return pthread_cond_init( &p_condvar->cond, NULL );
403
404 #elif defined( HAVE_CTHREADS_H )
405     /* condition_init() */
406     spin_lock_init( &p_condvar->lock );
407     cthread_queue_init( &p_condvar->queue );
408     p_condvar->name = 0;
409     p_condvar->implications = 0;
410
411     return 0;
412
413 #elif defined( HAVE_KERNEL_SCHEDULER_H )
414     if( !p_condvar )
415     {
416         return B_BAD_VALUE;
417     }
418
419     if( p_condvar->init == 9999 )
420     {
421         return EALREADY;
422     }
423
424     p_condvar->thread = -1;
425     p_condvar->init = 9999;
426     return 0;
427 #endif
428 }
429
430 /*****************************************************************************
431  * vlc_cond_destroy: destroy a condition, inner version
432  *****************************************************************************/
433 int __vlc_cond_destroy( char * psz_file, int i_line, vlc_cond_t *p_condvar )
434 {
435     int i_result;
436     /* In case of error : */
437     int i_thread = -1;
438     const char * psz_error = "";
439
440 #if defined( PTH_INIT_IN_PTH_H )
441     return 0;
442
443 #elif defined( ST_INIT_IN_ST_H )
444     i_result = st_cond_destroy( *p_condvar->cond );
445
446 #elif defined( WIN32 )
447     if( !p_condvar->semaphore )
448         i_result = !CloseHandle( p_condvar->event );
449     else
450         i_result = !CloseHandle( p_condvar->event )
451           || !CloseHandle( p_condvar->semaphore );
452
453 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
454     i_result = pthread_cond_destroy( &p_condvar->cond );
455     if ( i_result )
456     {
457         i_thread = pthread_self();
458         psz_error = strerror(i_result);
459     }
460
461 #elif defined( HAVE_CTHREADS_H )
462     return 0;
463
464 #elif defined( HAVE_KERNEL_SCHEDULER_H )
465     p_condvar->init = 0;
466     return 0;
467 #endif
468
469     if( i_result )
470     {
471         msg_Err( p_condvar->p_this,
472                  "thread %d: cond_destroy failed at %s:%d (%d:%s)",
473                  i_thread, psz_file, i_line, i_result, psz_error );
474     }
475     return i_result;
476 }
477
478 /*****************************************************************************
479  * vlc_thread_create: create a thread, inner version
480  *****************************************************************************
481  * Note that i_priority is only taken into account on platforms supporting
482  * userland real-time priority threads.
483  *****************************************************************************/
484 int __vlc_thread_create( vlc_object_t *p_this, char * psz_file, int i_line,
485                          char *psz_name, void * ( *func ) ( void * ),
486                          int i_priority, vlc_bool_t b_wait )
487 {
488     int i_ret;
489
490     vlc_mutex_lock( &p_this->object_lock );
491
492 #ifdef GPROF
493     wrapper_t wrapper;
494
495     /* Initialize the wrapper structure */
496     wrapper.func = func;
497     wrapper.p_data = (void *)p_this;
498     getitimer( ITIMER_PROF, &wrapper.itimer );
499     vlc_mutex_init( p_this, &wrapper.lock );
500     vlc_cond_init( p_this, &wrapper.wait );
501     vlc_mutex_lock( &wrapper.lock );
502
503     /* Alter user-passed data so that we call the wrapper instead
504      * of the real function */
505     p_data = &wrapper;
506     func = vlc_thread_wrapper;
507 #endif
508
509 #if defined( PTH_INIT_IN_PTH_H )
510     p_this->thread_id = pth_spawn( PTH_ATTR_DEFAULT, func, (void *)p_this );
511     i_ret = 0;
512
513 #elif defined( ST_INIT_IN_ST_H )
514     p_this->thread_id = st_thread_create( func, (void *)p_this, 1, 0 );
515     i_ret = 0;
516     
517 #elif defined( WIN32 )
518     {
519         unsigned threadID;
520         /* When using the MSVCRT C library you have to use the _beginthreadex
521          * function instead of CreateThread, otherwise you'll end up with
522          * memory leaks and the signal functions not working */
523         p_this->thread_id =
524                 (HANDLE)_beginthreadex( NULL, 0, (PTHREAD_START) func, 
525                                         (void *)p_this, 0, &threadID );
526     }
527
528     if ( p_this->thread_id && i_priority )
529     {
530         if ( !SetThreadPriority(p_this->thread_id, i_priority) )
531         {
532             msg_Warn( p_this, "couldn't set a faster priority" );
533             i_priority = 0;
534         }
535     }
536
537     i_ret = ( p_this->thread_id ? 0 : 1 );
538
539 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
540     i_ret = pthread_create( &p_this->thread_id, NULL, func, (void *)p_this );
541
542     if ( i_priority )
543     {
544         struct sched_param param;
545         memset( &param, 0, sizeof(struct sched_param) );
546         param.sched_priority = i_priority;
547         if ( pthread_setschedparam( p_this->thread_id, SCHED_RR, &param ) )
548         {
549             msg_Warn( p_this, "couldn't go to real-time priority" );
550             i_priority = 0;
551         }
552     }
553
554 #elif defined( HAVE_CTHREADS_H )
555     p_this->thread_id = cthread_fork( (cthread_fn_t)func, (any_t)p_this );
556     i_ret = 0;
557
558 #elif defined( HAVE_KERNEL_SCHEDULER_H )
559     p_this->thread_id = spawn_thread( (thread_func)func, psz_name,
560                                       B_NORMAL_PRIORITY, (void *)p_this );
561     i_ret = resume_thread( p_this->thread_id );
562
563 #endif
564
565 #ifdef GPROF
566     if( i_ret == 0 )
567     {
568         vlc_cond_wait( &wrapper.wait, &wrapper.lock );
569     }
570
571     vlc_mutex_unlock( &wrapper.lock );
572     vlc_mutex_destroy( &wrapper.lock );
573     vlc_cond_destroy( &wrapper.wait );
574 #endif
575
576     if( i_ret == 0 )
577     {
578         if( b_wait )
579         {
580             msg_Dbg( p_this, "waiting for thread completion" );
581             vlc_cond_wait( &p_this->object_wait, &p_this->object_lock );
582         }
583
584         p_this->b_thread = 1;
585
586         msg_Dbg( p_this, "thread %d (%s) created at priority %d (%s:%d)",
587                  p_this->thread_id, psz_name, i_priority,
588                  psz_file, i_line );
589
590         vlc_mutex_unlock( &p_this->object_lock );
591     }
592     else
593     {
594         msg_Err( p_this, "%s thread could not be created at %s:%d (%s)",
595                          psz_name, psz_file, i_line, strerror(i_ret) );
596         vlc_mutex_unlock( &p_this->object_lock );
597     }
598
599     return i_ret;
600 }
601
602 /*****************************************************************************
603  * vlc_thread_ready: tell the parent thread we were successfully spawned
604  *****************************************************************************/
605 void __vlc_thread_ready( vlc_object_t *p_this )
606 {
607     vlc_mutex_lock( &p_this->object_lock );
608     vlc_cond_signal( &p_this->object_wait );
609     vlc_mutex_unlock( &p_this->object_lock );
610 }
611
612 /*****************************************************************************
613  * vlc_thread_join: wait until a thread exits, inner version
614  *****************************************************************************/
615 void __vlc_thread_join( vlc_object_t *p_this, char * psz_file, int i_line )
616 {
617     int i_ret = 0;
618
619 #if defined( PTH_INIT_IN_PTH_H )
620     i_ret = pth_join( p_this->thread_id, NULL );
621
622 #elif defined( ST_INIT_IN_ST_H )
623     i_ret = st_thread_join( p_this->thread_id, NULL );
624     
625 #elif defined( WIN32 )
626     WaitForSingleObject( p_this->thread_id, INFINITE );
627
628 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
629     i_ret = pthread_join( p_this->thread_id, NULL );
630
631 #elif defined( HAVE_CTHREADS_H )
632     cthread_join( p_this->thread_id );
633     i_ret = 1;
634
635 #elif defined( HAVE_KERNEL_SCHEDULER_H )
636     int32 exit_value;
637     wait_for_thread( p_this->thread_id, &exit_value );
638
639 #endif
640
641     if( i_ret )
642     {
643         msg_Err( p_this, "thread_join(%d) failed at %s:%d (%s)",
644                          p_this->thread_id, psz_file, i_line, strerror(i_ret) );
645     }
646     else
647     {
648         msg_Dbg( p_this, "thread %d joined (%s:%d)",
649                          p_this->thread_id, psz_file, i_line );
650     }
651
652     p_this->b_thread = 0;
653 }
654
655 /*****************************************************************************
656  * vlc_thread_wrapper: wrapper around thread functions used when profiling.
657  *****************************************************************************/
658 #ifdef GPROF
659 static void *vlc_thread_wrapper( void *p_wrapper )
660 {
661     /* Put user data in thread-local variables */
662     void *            p_data = ((wrapper_t*)p_wrapper)->p_data;
663     vlc_thread_func_t func   = ((wrapper_t*)p_wrapper)->func;
664
665     /* Set the profile timer value */
666     setitimer( ITIMER_PROF, &((wrapper_t*)p_wrapper)->itimer, NULL );
667
668     /* Tell the calling thread that we don't need its data anymore */
669     vlc_mutex_lock( &((wrapper_t*)p_wrapper)->lock );
670     vlc_cond_signal( &((wrapper_t*)p_wrapper)->wait );
671     vlc_mutex_unlock( &((wrapper_t*)p_wrapper)->lock );
672
673     /* Call the real function */
674     return func( p_data );
675 }
676 #endif