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