]> git.sesse.net Git - vlc/blob - src/misc/threads.c
* ./src/misc/threads.c: fixed a bug in the st_mutex_new() failure detection.
[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.17 2002/09/29 18:16:04 sam 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     HINSTANCE hInstLib;
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         /* dynamically get the address of SignalObjectAndWait */
126         if( GetVersion() < 0x80000000 )
127         {
128             /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
129             hInstLib = LoadLibrary( "kernel32" );
130             if( hInstLib )
131             {
132                 p_this->p_vlc->SignalObjectAndWait =
133                     (SIGNALOBJECTANDWAIT)GetProcAddress( hInstLib,
134                                                      "SignalObjectAndWait" );
135             }
136         }
137         else
138         {
139             p_this->p_vlc->SignalObjectAndWait = NULL;
140         }
141
142         p_this->p_vlc->b_fast_mutex = 0;
143         p_this->p_vlc->i_win9x_cv = 0;
144
145 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
146         /* Unimplemented */
147 #elif defined( HAVE_CTHREADS_H )
148         /* Unimplemented */
149 #elif defined( HAVE_KERNEL_SCHEDULER_H )
150         /* Unimplemented */
151 #endif
152
153         if( i_ret )
154         {
155             i_status = VLC_THREADS_ERROR;
156         }
157         else
158         {
159             vlc_mutex_init( p_this, p_this->p_vlc->p_global_lock );
160             i_status = VLC_THREADS_READY;
161         }
162     }
163     else
164     {
165         i_ret = ( i_status == VLC_THREADS_READY );
166     }
167
168     i_initializations++;
169
170 #if defined( PTH_INIT_IN_PTH_H )
171     /* Unimplemented */
172 #elif defined( ST_INIT_IN_ST_H )
173     /* Unimplemented */
174 #elif defined( WIN32 )
175     /* Unimplemented */
176 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
177     pthread_mutex_unlock( &once_mutex );
178     return i_ret;
179 #elif defined( HAVE_CTHREADS_H )
180     /* Unimplemented */
181 #elif defined( HAVE_KERNEL_SCHEDULER_H )
182     /* Unimplemented */
183 #endif
184
185     /* Wait until the other thread has initialized the thread library */
186     while( i_status == VLC_THREADS_PENDING )
187     {
188         msleep( THREAD_SLEEP );
189     }
190
191     return i_status == VLC_THREADS_READY;
192 }
193
194 /*****************************************************************************
195  * vlc_threads_end: stop threads system
196  *****************************************************************************
197  * FIXME: This function is far from being threadsafe. We should undo exactly
198  * what we did above in vlc_threads_init.
199  *****************************************************************************/
200 int __vlc_threads_end( vlc_object_t *p_this )
201 {
202 #if defined( PTH_INIT_IN_PTH_H )
203     i_initializations--;
204     if( i_initializations == 0 )
205     {
206         return pth_kill();
207     }
208     return 0;
209
210 #elif defined( ST_INIT_IN_ST_H )
211     i_initializations--;
212     return 0;
213
214 #elif defined( WIN32 )
215     i_initializations--;
216     return 0;
217
218 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
219     pthread_mutex_lock( &once_mutex );
220     i_initializations--;
221     pthread_mutex_unlock( &once_mutex );
222     return 0;
223
224 #elif defined( HAVE_CTHREADS_H )
225     i_initializations--;
226     return 0;
227
228 #elif defined( HAVE_KERNEL_SCHEDULER_H )
229     i_initializations--;
230     return 0;
231
232 #endif
233 }
234
235 /*****************************************************************************
236  * vlc_mutex_init: initialize a mutex
237  *****************************************************************************/
238 int __vlc_mutex_init( vlc_object_t *p_this, vlc_mutex_t *p_mutex )
239 {
240     p_mutex->p_this = p_this;
241
242 #if defined( PTH_INIT_IN_PTH_H )
243     return pth_mutex_init( &p_mutex->mutex );
244
245 #elif defined( ST_INIT_IN_ST_H )
246     p_mutex->mutex = st_mutex_new();
247     return ( p_mutex->mutex == NULL ) ? errno : 0;
248
249 #elif defined( WIN32 )
250     /* We use mutexes on WinNT/2K/XP because we can use the SignalObjectAndWait
251      * function and have a 100% correct vlc_cond_wait() implementation.
252      * As this function is not available on Win9x, we can use the faster
253      * CriticalSections */
254     if( p_this->p_vlc->SignalObjectAndWait && !p_this->p_vlc->b_fast_mutex )
255     {
256         /* We are running on NT/2K/XP, we can use SignalObjectAndWait */
257         p_mutex->mutex = CreateMutex( 0, FALSE, 0 );
258         return ( p_mutex->mutex != NULL ? 0 : 1 );
259     }
260     else
261     {
262         p_mutex->mutex = NULL;
263         InitializeCriticalSection( &p_mutex->csection );
264         return 0;
265     }
266
267 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
268 #   if defined(DEBUG) && defined(SYS_LINUX)
269     {
270         /* Create error-checking mutex to detect problems more easily. */
271         pthread_mutexattr_t attr;
272         int                 i_result;
273
274         pthread_mutexattr_init( &attr );
275         pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
276         i_result = pthread_mutex_init( &p_mutex->mutex, &attr );
277         pthread_mutexattr_destroy( &attr );
278         return( i_result );
279     }
280 #   endif
281     return pthread_mutex_init( &p_mutex->mutex, NULL );
282
283 #elif defined( HAVE_CTHREADS_H )
284     mutex_init( p_mutex );
285     return 0;
286
287 #elif defined( HAVE_KERNEL_SCHEDULER_H )
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 #endif
309 }
310
311 /*****************************************************************************
312  * vlc_mutex_destroy: destroy a mutex, inner version
313  *****************************************************************************/
314 int __vlc_mutex_destroy( char * psz_file, int i_line, vlc_mutex_t *p_mutex )
315 {
316     int i_result;
317     /* In case of error : */
318     int i_thread = -1;
319     const char * psz_error = "";
320
321 #if defined( PTH_INIT_IN_PTH_H )
322     return 0;
323
324 #elif defined( ST_INIT_IN_ST_H )
325     i_result = st_mutex_destroy( p_mutex->mutex );
326
327 #elif defined( WIN32 )
328     if( p_mutex->mutex )
329     {
330         CloseHandle( p_mutex->mutex );
331     }
332     else
333     {
334         DeleteCriticalSection( &p_mutex->csection );
335     }
336     return 0;
337
338 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )    
339     i_result = pthread_mutex_destroy( &p_mutex->mutex );
340     if ( i_result )
341     {
342         i_thread = (int)pthread_self();
343         psz_error = strerror(i_result);
344     }
345
346 #elif defined( HAVE_CTHREADS_H )
347     return 0;
348
349 #elif defined( HAVE_KERNEL_SCHEDULER_H )
350     if( p_mutex->init == 9999 )
351     {
352         delete_sem( p_mutex->lock );
353     }
354
355     p_mutex->init = 0;
356     return B_OK;
357 #endif    
358
359     if( i_result )
360     {
361         msg_Err( p_mutex->p_this,
362                  "thread %d: mutex_destroy failed at %s:%d (%d:%s)",
363                  i_thread, psz_file, i_line, i_result, psz_error );
364     }
365     return i_result;
366 }
367
368 /*****************************************************************************
369  * vlc_cond_init: initialize a condition
370  *****************************************************************************/
371 int __vlc_cond_init( vlc_object_t *p_this, vlc_cond_t *p_condvar )
372 {
373     p_condvar->p_this = p_this;
374
375 #if defined( PTH_INIT_IN_PTH_H )
376     return pth_cond_init( &p_condvar->cond );
377
378 #elif defined( ST_INIT_IN_ST_H )
379     p_condvar->cond = st_cond_new();
380     return ( p_condvar->cond == NULL ) ? errno : 0;
381
382 #elif defined( WIN32 )
383     /* Initialize counter */
384     p_condvar->i_waiting_threads = 0;
385
386     /* Misc init */
387     p_condvar->i_win9x_cv = p_this->p_vlc->i_win9x_cv;
388     p_condvar->SignalObjectAndWait = p_this->p_vlc->SignalObjectAndWait;
389
390     if( p_this->p_vlc->i_win9x_cv == 0 )
391     {
392         /* Create an auto-reset event. */
393         p_condvar->event = CreateEvent( NULL,   /* no security */
394                                         FALSE,  /* auto-reset event */
395                                         FALSE,  /* start non-signaled */
396                                         NULL ); /* unnamed */
397
398         p_condvar->semaphore = NULL;
399         return !p_condvar->event;
400     }
401     else
402     {
403         p_condvar->semaphore = CreateSemaphore( NULL,       /* no security */
404                                                 0,          /* initial count */
405                                                 0x7fffffff, /* max count */
406                                                 NULL );     /* unnamed */
407
408         if( p_this->p_vlc->i_win9x_cv == 1 )
409             /* Create a manual-reset event initially signaled. */
410             p_condvar->event = CreateEvent( NULL, TRUE, TRUE, NULL );
411         else
412             /* Create a auto-reset event. */
413             p_condvar->event = CreateEvent( NULL, FALSE, FALSE, NULL );
414
415         InitializeCriticalSection( &p_condvar->csection );
416
417         return !p_condvar->semaphore || !p_condvar->event;
418     }
419
420 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
421     return pthread_cond_init( &p_condvar->cond, NULL );
422
423 #elif defined( HAVE_CTHREADS_H )
424     /* condition_init() */
425     spin_lock_init( &p_condvar->lock );
426     cthread_queue_init( &p_condvar->queue );
427     p_condvar->name = 0;
428     p_condvar->implications = 0;
429
430     return 0;
431
432 #elif defined( HAVE_KERNEL_SCHEDULER_H )
433     if( !p_condvar )
434     {
435         return B_BAD_VALUE;
436     }
437
438     if( p_condvar->init == 9999 )
439     {
440         return EALREADY;
441     }
442
443     p_condvar->thread = -1;
444     p_condvar->init = 9999;
445     return 0;
446 #endif
447 }
448
449 /*****************************************************************************
450  * vlc_cond_destroy: destroy a condition, inner version
451  *****************************************************************************/
452 int __vlc_cond_destroy( char * psz_file, int i_line, vlc_cond_t *p_condvar )
453 {
454     int i_result;
455     /* In case of error : */
456     int i_thread = -1;
457     const char * psz_error = "";
458
459 #if defined( PTH_INIT_IN_PTH_H )
460     return 0;
461
462 #elif defined( ST_INIT_IN_ST_H )
463     i_result = st_cond_destroy( p_condvar->cond );
464
465 #elif defined( WIN32 )
466     if( !p_condvar->semaphore )
467         i_result = !CloseHandle( p_condvar->event );
468     else
469         i_result = !CloseHandle( p_condvar->event )
470           || !CloseHandle( p_condvar->semaphore );
471
472 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
473     i_result = pthread_cond_destroy( &p_condvar->cond );
474     if ( i_result )
475     {
476         i_thread = (int)pthread_self();
477         psz_error = strerror(i_result);
478     }
479
480 #elif defined( HAVE_CTHREADS_H )
481     return 0;
482
483 #elif defined( HAVE_KERNEL_SCHEDULER_H )
484     p_condvar->init = 0;
485     return 0;
486 #endif
487
488     if( i_result )
489     {
490         msg_Err( p_condvar->p_this,
491                  "thread %d: cond_destroy failed at %s:%d (%d:%s)",
492                  i_thread, psz_file, i_line, i_result, psz_error );
493     }
494     return i_result;
495 }
496
497 /*****************************************************************************
498  * vlc_thread_create: create a thread, inner version
499  *****************************************************************************
500  * Note that i_priority is only taken into account on platforms supporting
501  * userland real-time priority threads.
502  *****************************************************************************/
503 int __vlc_thread_create( vlc_object_t *p_this, char * psz_file, int i_line,
504                          char *psz_name, void * ( *func ) ( void * ),
505                          int i_priority, vlc_bool_t b_wait )
506 {
507     int i_ret;
508
509     vlc_mutex_lock( &p_this->object_lock );
510
511 #ifdef GPROF
512     wrapper_t wrapper;
513
514     /* Initialize the wrapper structure */
515     wrapper.func = func;
516     wrapper.p_data = (void *)p_this;
517     getitimer( ITIMER_PROF, &wrapper.itimer );
518     vlc_mutex_init( p_this, &wrapper.lock );
519     vlc_cond_init( p_this, &wrapper.wait );
520     vlc_mutex_lock( &wrapper.lock );
521
522     /* Alter user-passed data so that we call the wrapper instead
523      * of the real function */
524     p_data = &wrapper;
525     func = vlc_thread_wrapper;
526 #endif
527
528 #if defined( PTH_INIT_IN_PTH_H )
529     p_this->thread_id = pth_spawn( PTH_ATTR_DEFAULT, func, (void *)p_this );
530     i_ret = 0;
531
532 #elif defined( ST_INIT_IN_ST_H )
533     p_this->thread_id = st_thread_create( func, (void *)p_this, 1, 0 );
534     i_ret = 0;
535     
536 #elif defined( WIN32 )
537     {
538         unsigned threadID;
539         /* When using the MSVCRT C library you have to use the _beginthreadex
540          * function instead of CreateThread, otherwise you'll end up with
541          * memory leaks and the signal functions not working */
542         p_this->thread_id =
543                 (HANDLE)_beginthreadex( NULL, 0, (PTHREAD_START) func, 
544                                         (void *)p_this, 0, &threadID );
545     }
546
547     if ( p_this->thread_id && i_priority )
548     {
549         if ( !SetThreadPriority(p_this->thread_id, i_priority) )
550         {
551             msg_Warn( p_this, "couldn't set a faster priority" );
552             i_priority = 0;
553         }
554     }
555
556     i_ret = ( p_this->thread_id ? 0 : 1 );
557
558 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
559     i_ret = pthread_create( &p_this->thread_id, NULL, func, (void *)p_this );
560
561     if ( i_priority )
562     {
563         struct sched_param param;
564         memset( &param, 0, sizeof(struct sched_param) );
565         param.sched_priority = i_priority;
566         if ( pthread_setschedparam( p_this->thread_id, SCHED_RR, &param ) )
567         {
568             msg_Warn( p_this, "couldn't go to real-time priority" );
569             i_priority = 0;
570         }
571     }
572
573 #elif defined( HAVE_CTHREADS_H )
574     p_this->thread_id = cthread_fork( (cthread_fn_t)func, (any_t)p_this );
575     i_ret = 0;
576
577 #elif defined( HAVE_KERNEL_SCHEDULER_H )
578     p_this->thread_id = spawn_thread( (thread_func)func, psz_name,
579                                       B_NORMAL_PRIORITY, (void *)p_this );
580     i_ret = resume_thread( p_this->thread_id );
581
582 #endif
583
584 #ifdef GPROF
585     if( i_ret == 0 )
586     {
587         vlc_cond_wait( &wrapper.wait, &wrapper.lock );
588     }
589
590     vlc_mutex_unlock( &wrapper.lock );
591     vlc_mutex_destroy( &wrapper.lock );
592     vlc_cond_destroy( &wrapper.wait );
593 #endif
594
595     if( i_ret == 0 )
596     {
597         if( b_wait )
598         {
599             msg_Dbg( p_this, "waiting for thread completion" );
600             vlc_cond_wait( &p_this->object_wait, &p_this->object_lock );
601         }
602
603         p_this->b_thread = 1;
604
605         msg_Dbg( p_this, "thread %d (%s) created at priority %d (%s:%d)",
606                  p_this->thread_id, psz_name, i_priority,
607                  psz_file, i_line );
608
609         vlc_mutex_unlock( &p_this->object_lock );
610     }
611     else
612     {
613         msg_Err( p_this, "%s thread could not be created at %s:%d (%s)",
614                          psz_name, psz_file, i_line, strerror(i_ret) );
615         vlc_mutex_unlock( &p_this->object_lock );
616     }
617
618     return i_ret;
619 }
620
621 /*****************************************************************************
622  * vlc_thread_ready: tell the parent thread we were successfully spawned
623  *****************************************************************************/
624 void __vlc_thread_ready( vlc_object_t *p_this )
625 {
626     vlc_mutex_lock( &p_this->object_lock );
627     vlc_cond_signal( &p_this->object_wait );
628     vlc_mutex_unlock( &p_this->object_lock );
629 }
630
631 /*****************************************************************************
632  * vlc_thread_join: wait until a thread exits, inner version
633  *****************************************************************************/
634 void __vlc_thread_join( vlc_object_t *p_this, char * psz_file, int i_line )
635 {
636     int i_ret = 0;
637
638 #if defined( PTH_INIT_IN_PTH_H )
639     i_ret = pth_join( p_this->thread_id, NULL );
640
641 #elif defined( ST_INIT_IN_ST_H )
642     i_ret = st_thread_join( p_this->thread_id, NULL );
643     
644 #elif defined( WIN32 )
645     WaitForSingleObject( p_this->thread_id, INFINITE );
646
647 #elif defined( PTHREAD_COND_T_IN_PTHREAD_H )
648     i_ret = pthread_join( p_this->thread_id, NULL );
649
650 #elif defined( HAVE_CTHREADS_H )
651     cthread_join( p_this->thread_id );
652     i_ret = 1;
653
654 #elif defined( HAVE_KERNEL_SCHEDULER_H )
655     int32 exit_value;
656     wait_for_thread( p_this->thread_id, &exit_value );
657
658 #endif
659
660     if( i_ret )
661     {
662         msg_Err( p_this, "thread_join(%d) failed at %s:%d (%s)",
663                          p_this->thread_id, psz_file, i_line, strerror(i_ret) );
664     }
665     else
666     {
667         msg_Dbg( p_this, "thread %d joined (%s:%d)",
668                          p_this->thread_id, psz_file, i_line );
669     }
670
671     p_this->b_thread = 0;
672 }
673
674 /*****************************************************************************
675  * vlc_thread_wrapper: wrapper around thread functions used when profiling.
676  *****************************************************************************/
677 #ifdef GPROF
678 static void *vlc_thread_wrapper( void *p_wrapper )
679 {
680     /* Put user data in thread-local variables */
681     void *            p_data = ((wrapper_t*)p_wrapper)->p_data;
682     vlc_thread_func_t func   = ((wrapper_t*)p_wrapper)->func;
683
684     /* Set the profile timer value */
685     setitimer( ITIMER_PROF, &((wrapper_t*)p_wrapper)->itimer, NULL );
686
687     /* Tell the calling thread that we don't need its data anymore */
688     vlc_mutex_lock( &((wrapper_t*)p_wrapper)->lock );
689     vlc_cond_signal( &((wrapper_t*)p_wrapper)->wait );
690     vlc_mutex_unlock( &((wrapper_t*)p_wrapper)->lock );
691
692     /* Call the real function */
693     return func( p_data );
694 }
695 #endif