]> git.sesse.net Git - vlc/blob - src/misc/threads.c
Fix the kludge for old glibc
[vlc] / src / misc / threads.c
1 /*****************************************************************************
2  * threads.c : threads implementation for the VideoLAN client
3  *****************************************************************************
4  * Copyright (C) 1999-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          Gildas Bazin <gbazin@netcourrier.com>
10  *          Clément Sténac
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc/vlc.h>
32
33 #include "libvlc.h"
34 #include <assert.h>
35 #ifdef HAVE_UNISTD_H
36 # include <unistd.h>
37 #endif
38
39 #define VLC_THREADS_UNINITIALIZED  0
40 #define VLC_THREADS_PENDING        1
41 #define VLC_THREADS_ERROR          2
42 #define VLC_THREADS_READY          3
43
44 /*****************************************************************************
45  * Global mutex for lazy initialization of the threads system
46  *****************************************************************************/
47 static volatile unsigned i_initializations = 0;
48
49 #if defined( LIBVLC_USE_PTHREAD )
50 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
51 #endif
52
53 /**
54  * Global process-wide VLC object.
55  * Contains inter-instance data, such as the module cache and global mutexes.
56  */
57 static libvlc_global_data_t *p_root;
58
59 libvlc_global_data_t *vlc_global( void )
60 {
61     assert( i_initializations > 0 );
62     return p_root;
63 }
64
65
66 vlc_threadvar_t msg_context_global_key;
67
68 #if defined(LIBVLC_USE_PTHREAD)
69 static inline unsigned long vlc_threadid (void)
70 {
71      union { pthread_t th; unsigned long int i; } v = { };
72      v.th = pthread_self ();
73      return v.i;
74 }
75
76
77 /*****************************************************************************
78  * vlc_thread_fatal: Report an error from the threading layer
79  *****************************************************************************
80  * This is mostly meant for debugging.
81  *****************************************************************************/
82 void vlc_pthread_fatal (const char *action, int error,
83                         const char *file, unsigned line)
84 {
85     fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
86              action, vlc_threadid (), file, line, error);
87     fflush (stderr);
88
89     /* Sometimes strerror_r() crashes too, so make sure we print an error
90      * message before we invoke it */
91 #ifdef __GLIBC__
92     /* Avoid the strerror_r() prototype brain damage in glibc */
93     errno = error;
94     fprintf (stderr, " Error message: %m\n");
95 #else
96     char buf[1000];
97     const char *msg;
98
99     switch (strerror_r (error, buf, sizeof (buf)))
100     {
101         case 0:
102             msg = buf;
103             break;
104         case ERANGE: /* should never happen */
105             msg = "unknwon (too big to display)";
106             break;
107         default:
108             msg = "unknown (invalid error number)";
109             break;
110     }
111     fprintf (stderr, " Error message: %s\n", msg);
112 #endif
113
114     fflush (stderr);
115     abort ();
116 }
117 #endif
118
119
120 /*****************************************************************************
121  * vlc_threads_init: initialize threads system
122  *****************************************************************************
123  * This function requires lazy initialization of a global lock in order to
124  * keep the library really thread-safe. Some architectures don't support this
125  * and thus do not guarantee the complete reentrancy.
126  *****************************************************************************/
127 int vlc_threads_init( void )
128 {
129     int i_ret = VLC_SUCCESS;
130
131     /* If we have lazy mutex initialization, use it. Otherwise, we just
132      * hope nothing wrong happens. */
133 #if defined( LIBVLC_USE_PTHREAD )
134     pthread_mutex_lock( &once_mutex );
135 #endif
136
137     if( i_initializations == 0 )
138     {
139         p_root = vlc_custom_create( NULL, sizeof( *p_root ),
140                                     VLC_OBJECT_GENERIC, "root" );
141         if( p_root == NULL )
142         {
143             i_ret = VLC_ENOMEM;
144             goto out;
145         }
146
147         /* We should be safe now. Do all the initialization stuff we want. */
148         vlc_threadvar_create( p_root, &msg_context_global_key );
149     }
150     i_initializations++;
151
152 out:
153     /* If we have lazy mutex initialization support, unlock the mutex.
154      * Otherwize, we are screwed. */
155 #if defined( LIBVLC_USE_PTHREAD )
156     pthread_mutex_unlock( &once_mutex );
157 #endif
158
159     return i_ret;
160 }
161
162 /*****************************************************************************
163  * vlc_threads_end: stop threads system
164  *****************************************************************************
165  * FIXME: This function is far from being threadsafe.
166  *****************************************************************************/
167 void vlc_threads_end( void )
168 {
169 #if defined( LIBVLC_USE_PTHREAD )
170     pthread_mutex_lock( &once_mutex );
171 #endif
172
173     assert( i_initializations > 0 );
174
175     if( i_initializations == 1 )
176         vlc_object_release( p_root );
177     i_initializations--;
178
179 #if defined( LIBVLC_USE_PTHREAD )
180     pthread_mutex_unlock( &once_mutex );
181 #endif
182 }
183
184 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
185 /* This is not prototyped under glibc, though it exists. */
186 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
187 #endif
188
189 /*****************************************************************************
190  * vlc_mutex_init: initialize a mutex
191  *****************************************************************************/
192 int vlc_mutex_init( vlc_mutex_t *p_mutex )
193 {
194 #if defined( LIBVLC_USE_PTHREAD )
195     pthread_mutexattr_t attr;
196     int                 i_result;
197
198     pthread_mutexattr_init( &attr );
199
200 # ifndef NDEBUG
201     /* Create error-checking mutex to detect problems more easily. */
202 #  if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
203     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
204 #  else
205     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
206 #  endif
207 # endif
208     i_result = pthread_mutex_init( p_mutex, &attr );
209     pthread_mutexattr_destroy( &attr );
210     return i_result;
211 #elif defined( UNDER_CE )
212     InitializeCriticalSection( &p_mutex->csection );
213     return 0;
214
215 #elif defined( WIN32 )
216     *p_mutex = CreateMutex( 0, FALSE, 0 );
217     return (*p_mutex != NULL) ? 0 : ENOMEM;
218
219 #elif defined( HAVE_KERNEL_SCHEDULER_H )
220     /* check the arguments and whether it's already been initialized */
221     if( p_mutex == NULL )
222     {
223         return B_BAD_VALUE;
224     }
225
226     if( p_mutex->init == 9999 )
227     {
228         return EALREADY;
229     }
230
231     p_mutex->lock = create_sem( 1, "BeMutex" );
232     if( p_mutex->lock < B_NO_ERROR )
233     {
234         return( -1 );
235     }
236
237     p_mutex->init = 9999;
238     return B_OK;
239
240 #endif
241 }
242
243 /*****************************************************************************
244  * vlc_mutex_init: initialize a recursive mutex (Do not use)
245  *****************************************************************************/
246 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
247 {
248 #if defined( LIBVLC_USE_PTHREAD )
249     pthread_mutexattr_t attr;
250     int                 i_result;
251
252     pthread_mutexattr_init( &attr );
253 #  if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
254     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
255 #  else
256     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
257 #  endif
258     i_result = pthread_mutex_init( p_mutex, &attr );
259     pthread_mutexattr_destroy( &attr );
260     return( i_result );
261 #elif defined( WIN32 )
262     /* Create mutex returns a recursive mutex */
263     *p_mutex = CreateMutex( 0, FALSE, 0 );
264     return (*p_mutex != NULL) ? 0 : ENOMEM;
265 #else
266 # error Unimplemented!
267 #endif
268 }
269
270
271 /*****************************************************************************
272  * vlc_mutex_destroy: destroy a mutex, inner version
273  *****************************************************************************/
274 void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mutex )
275 {
276 #if defined( LIBVLC_USE_PTHREAD )
277     int val = pthread_mutex_destroy( p_mutex );
278     VLC_THREAD_ASSERT ("destroying mutex");
279
280 #elif defined( UNDER_CE )
281     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
282
283     DeleteCriticalSection( &p_mutex->csection );
284
285 #elif defined( WIN32 )
286     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
287
288     CloseHandle( *p_mutex );
289
290 #elif defined( HAVE_KERNEL_SCHEDULER_H )
291     if( p_mutex->init == 9999 )
292         delete_sem( p_mutex->lock );
293
294     p_mutex->init = 0;
295
296 #endif
297 }
298
299 /*****************************************************************************
300  * vlc_cond_init: initialize a condition
301  *****************************************************************************/
302 int __vlc_cond_init( vlc_cond_t *p_condvar )
303 {
304 #if defined( LIBVLC_USE_PTHREAD )
305     pthread_condattr_t attr;
306     int ret;
307
308     ret = pthread_condattr_init (&attr);
309     if (ret)
310         return ret;
311
312 # if !defined (_POSIX_CLOCK_SELECTION)
313    /* Fairly outdated POSIX support (that was defined in 2001) */
314 #  define _POSIX_CLOCK_SELECTION (-1)
315 # endif
316 # if (_POSIX_CLOCK_SELECTION >= 0)
317     /* NOTE: This must be the same clock as the one in mtime.c */
318     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
319 # endif
320
321     ret = pthread_cond_init (p_condvar, &attr);
322     pthread_condattr_destroy (&attr);
323     return ret;
324
325 #elif defined( UNDER_CE ) || defined( WIN32 )
326     /* Initialize counter */
327     p_condvar->i_waiting_threads = 0;
328
329     /* Create an auto-reset event. */
330     p_condvar->event = CreateEvent( NULL,   /* no security */
331                                     FALSE,  /* auto-reset event */
332                                     FALSE,  /* start non-signaled */
333                                     NULL ); /* unnamed */
334     return !p_condvar->event;
335
336 #elif defined( HAVE_KERNEL_SCHEDULER_H )
337     if( !p_condvar )
338     {
339         return B_BAD_VALUE;
340     }
341
342     if( p_condvar->init == 9999 )
343     {
344         return EALREADY;
345     }
346
347     p_condvar->thread = -1;
348     p_condvar->init = 9999;
349     return 0;
350
351 #endif
352 }
353
354 /*****************************************************************************
355  * vlc_cond_destroy: destroy a condition, inner version
356  *****************************************************************************/
357 void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condvar )
358 {
359 #if defined( LIBVLC_USE_PTHREAD )
360     int val = pthread_cond_destroy( p_condvar );
361     VLC_THREAD_ASSERT ("destroying condition");
362
363 #elif defined( UNDER_CE ) || defined( WIN32 )
364     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
365
366     CloseHandle( p_condvar->event );
367
368 #elif defined( HAVE_KERNEL_SCHEDULER_H )
369     p_condvar->init = 0;
370
371 #endif
372 }
373
374 /*****************************************************************************
375  * vlc_tls_create: create a thread-local variable
376  *****************************************************************************/
377 int __vlc_threadvar_create( vlc_threadvar_t *p_tls )
378 {
379     int i_ret = -1;
380
381 #if defined( LIBVLC_USE_PTHREAD )
382     i_ret =  pthread_key_create( p_tls, NULL );
383 #elif defined( UNDER_CE )
384 #elif defined( WIN32 )
385     *p_tls = TlsAlloc();
386     i_ret = (*p_tls == INVALID_HANDLE_VALUE) ? EAGAIN : 0;
387 #else
388 # error Unimplemented!
389 #endif
390     return i_ret;
391 }
392
393 /*****************************************************************************
394  * vlc_thread_create: create a thread, inner version
395  *****************************************************************************
396  * Note that i_priority is only taken into account on platforms supporting
397  * userland real-time priority threads.
398  *****************************************************************************/
399 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
400                          const char *psz_name, void * ( *func ) ( void * ),
401                          int i_priority, bool b_wait )
402 {
403     int i_ret;
404     void *p_data = (void *)p_this;
405     vlc_object_internals_t *p_priv = vlc_internals( p_this );
406
407     vlc_mutex_lock( &p_this->object_lock );
408
409 #if defined( LIBVLC_USE_PTHREAD )
410     i_ret = pthread_create( &p_priv->thread_id, NULL, func, p_data );
411
412 #ifndef __APPLE__
413     if( config_GetInt( p_this, "rt-priority" ) > 0 )
414 #endif
415     {
416         int i_error, i_policy;
417         struct sched_param param;
418
419         memset( &param, 0, sizeof(struct sched_param) );
420         if( config_GetType( p_this, "rt-offset" ) )
421             i_priority += config_GetInt( p_this, "rt-offset" );
422         if( i_priority <= 0 )
423         {
424             param.sched_priority = (-1) * i_priority;
425             i_policy = SCHED_OTHER;
426         }
427         else
428         {
429             param.sched_priority = i_priority;
430             i_policy = SCHED_RR;
431         }
432         if( (i_error = pthread_setschedparam( p_priv->thread_id,
433                                                i_policy, &param )) )
434         {
435             errno = i_error;
436             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
437                       psz_file, i_line );
438             i_priority = 0;
439         }
440     }
441 #ifndef __APPLE__
442     else
443         i_priority = 0;
444 #endif
445
446 #elif defined( WIN32 ) || defined( UNDER_CE )
447     {
448         /* When using the MSVCRT C library you have to use the _beginthreadex
449          * function instead of CreateThread, otherwise you'll end up with
450          * memory leaks and the signal functions not working (see Microsoft
451          * Knowledge Base, article 104641) */
452 #if defined( UNDER_CE )
453         DWORD  threadId;
454         HANDLE hThread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)func,
455                                       (LPVOID)p_data, CREATE_SUSPENDED,
456                       &threadId );
457 #else
458         unsigned threadId;
459         uintptr_t hThread = _beginthreadex( NULL, 0,
460                         (LPTHREAD_START_ROUTINE)func,
461                                             (void*)p_data, CREATE_SUSPENDED,
462                         &threadId );
463 #endif
464         p_priv->thread_id.id = (DWORD)threadId;
465         p_priv->thread_id.hThread = (HANDLE)hThread;
466         ResumeThread((HANDLE)hThread);
467     }
468
469     i_ret = ( p_priv->thread_id.hThread ? 0 : 1 );
470
471     if( !i_ret && i_priority )
472     {
473         if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
474         {
475             msg_Warn( p_this, "couldn't set a faster priority" );
476             i_priority = 0;
477         }
478     }
479
480 #elif defined( HAVE_KERNEL_SCHEDULER_H )
481     p_priv->thread_id = spawn_thread( (thread_func)func, psz_name,
482                                       i_priority, p_data );
483     i_ret = resume_thread( p_priv->thread_id );
484
485 #endif
486
487     if( i_ret == 0 )
488     {
489         if( b_wait )
490         {
491             msg_Dbg( p_this, "waiting for thread completion" );
492             vlc_object_wait( p_this );
493         }
494
495         p_priv->b_thread = true;
496
497 #if defined( WIN32 ) || defined( UNDER_CE )
498         msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
499                  (unsigned int)p_priv->thread_id.id, psz_name, i_priority,
500                  psz_file, i_line );
501 #else
502         msg_Dbg( p_this, "thread %u (%s) created at priority %d (%s:%d)",
503                  (unsigned int)p_priv->thread_id, psz_name, i_priority,
504                  psz_file, i_line );
505 #endif
506     }
507     else
508     {
509         errno = i_ret;
510         msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
511                          psz_name, psz_file, i_line );
512     }
513
514     vlc_mutex_unlock( &p_this->object_lock );
515     return i_ret;
516 }
517
518 /*****************************************************************************
519  * vlc_thread_set_priority: set the priority of the current thread when we
520  * couldn't set it in vlc_thread_create (for instance for the main thread)
521  *****************************************************************************/
522 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
523                                int i_line, int i_priority )
524 {
525     vlc_object_internals_t *p_priv = vlc_internals( p_this );
526
527 #if defined( LIBVLC_USE_PTHREAD )
528 # ifndef __APPLE__
529     if( config_GetInt( p_this, "rt-priority" ) > 0 )
530 # endif
531     {
532         int i_error, i_policy;
533         struct sched_param param;
534
535         memset( &param, 0, sizeof(struct sched_param) );
536         if( config_GetType( p_this, "rt-offset" ) )
537             i_priority += config_GetInt( p_this, "rt-offset" );
538         if( i_priority <= 0 )
539         {
540             param.sched_priority = (-1) * i_priority;
541             i_policy = SCHED_OTHER;
542         }
543         else
544         {
545             param.sched_priority = i_priority;
546             i_policy = SCHED_RR;
547         }
548         if( !p_priv->thread_id )
549             p_priv->thread_id = pthread_self();
550         if( (i_error = pthread_setschedparam( p_priv->thread_id,
551                                                i_policy, &param )) )
552         {
553             errno = i_error;
554             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
555                       psz_file, i_line );
556             i_priority = 0;
557         }
558     }
559
560 #elif defined( WIN32 ) || defined( UNDER_CE )
561     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
562
563     if( !p_priv->thread_id.hThread )
564         p_priv->thread_id.hThread = GetCurrentThread();
565     if( !SetThreadPriority(p_priv->thread_id.hThread, i_priority) )
566     {
567         msg_Warn( p_this, "couldn't set a faster priority" );
568         return 1;
569     }
570
571 #endif
572
573     return 0;
574 }
575
576 /*****************************************************************************
577  * vlc_thread_ready: tell the parent thread we were successfully spawned
578  *****************************************************************************/
579 void __vlc_thread_ready( vlc_object_t *p_this )
580 {
581     vlc_object_signal( p_this );
582 }
583
584 /*****************************************************************************
585  * vlc_thread_join: wait until a thread exits, inner version
586  *****************************************************************************/
587 void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
588 {
589     vlc_object_internals_t *p_priv = vlc_internals( p_this );
590     int i_ret = 0;
591
592 #if defined( LIBVLC_USE_PTHREAD )
593     /* Make sure we do return if we are calling vlc_thread_join()
594      * from the joined thread */
595     if (pthread_equal (pthread_self (), p_priv->thread_id))
596         i_ret = pthread_detach (p_priv->thread_id);
597     else
598         i_ret = pthread_join (p_priv->thread_id, NULL);
599
600 #elif defined( UNDER_CE ) || defined( WIN32 )
601     HMODULE hmodule;
602     BOOL (WINAPI *OurGetThreadTimes)( HANDLE, FILETIME*, FILETIME*,
603                                       FILETIME*, FILETIME* );
604     FILETIME create_ft, exit_ft, kernel_ft, user_ft;
605     int64_t real_time, kernel_time, user_time;
606     HANDLE hThread;
607
608     /*
609     ** object will close its thread handle when destroyed, duplicate it here
610     ** to be on the safe side
611     */
612     if( ! DuplicateHandle(GetCurrentProcess(),
613             p_priv->thread_id.hThread,
614             GetCurrentProcess(),
615             &hThread,
616             0,
617             FALSE,
618             DUPLICATE_SAME_ACCESS) )
619     {
620         msg_Err( p_this, "thread_join(%u) failed at %s:%d (%u)",
621                          (unsigned int)p_priv->thread_id.id,
622              psz_file, i_line, (unsigned int)GetLastError() );
623         p_priv->b_thread = false;
624         return;
625     }
626
627     WaitForSingleObject( hThread, INFINITE );
628
629     msg_Dbg( p_this, "thread %u joined (%s:%d)",
630              (unsigned int)p_priv->thread_id.id,
631              psz_file, i_line );
632 #if defined( UNDER_CE )
633     hmodule = GetModuleHandle( _T("COREDLL") );
634 #else
635     hmodule = GetModuleHandle( _T("KERNEL32") );
636 #endif
637     OurGetThreadTimes = (BOOL (WINAPI*)( HANDLE, FILETIME*, FILETIME*,
638                                          FILETIME*, FILETIME* ))
639         GetProcAddress( hmodule, _T("GetThreadTimes") );
640
641     if( OurGetThreadTimes &&
642         OurGetThreadTimes( hThread,
643                            &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
644     {
645         real_time =
646           ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
647           ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
648         real_time /= 10;
649
650         kernel_time =
651           ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
652            kernel_ft.dwLowDateTime) / 10;
653
654         user_time =
655           ((((int64_t)user_ft.dwHighDateTime)<<32)|
656            user_ft.dwLowDateTime) / 10;
657
658         msg_Dbg( p_this, "thread times: "
659                  "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
660                  real_time/60/1000000,
661                  (double)((real_time%(60*1000000))/1000000.0),
662                  kernel_time/60/1000000,
663                  (double)((kernel_time%(60*1000000))/1000000.0),
664                  user_time/60/1000000,
665                  (double)((user_time%(60*1000000))/1000000.0) );
666     }
667     CloseHandle( hThread );
668
669 #elif defined( HAVE_KERNEL_SCHEDULER_H )
670     int32_t exit_value;
671     i_ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
672
673 #endif
674
675     if( i_ret )
676     {
677         errno = i_ret;
678         msg_Err( p_this, "thread_join(%u) failed at %s:%d (%m)",
679                          (unsigned int)p_priv->thread_id, psz_file, i_line );
680     }
681     else
682         msg_Dbg( p_this, "thread %u joined (%s:%d)",
683                          (unsigned int)p_priv->thread_id, psz_file, i_line );
684
685     p_priv->b_thread = false;
686 }