codec: dvbsub: remove usage of bs_show
[vlc.git] / src / posix / thread.c
blobfc92102df691456635970a4db4bc684a22e7f1aa
1 /*****************************************************************************
2 * thread.c : pthread back-end for LibVLC
3 *****************************************************************************
4 * Copyright (C) 1999-2009 VLC authors and VideoLAN
6 * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
7 * Samuel Hocevar <sam@zoy.org>
8 * Gildas Bazin <gbazin@netcourrier.com>
9 * Clément Sténac
10 * Rémi Denis-Courmont
12 * This program is free software; you can redistribute it and/or modify it
13 * under the terms of the GNU Lesser General Public License as published by
14 * the Free Software Foundation; either version 2.1 of the License, or
15 * (at your option) any later version.
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 Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public License
23 * along with this program; if not, write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
31 #include <vlc_common.h>
33 #include "libvlc.h"
34 #include <stdarg.h>
35 #include <stdatomic.h>
36 #include <signal.h>
37 #include <errno.h>
38 #include <time.h>
39 #include <assert.h>
41 #include <sys/types.h>
42 #include <unistd.h> /* fsync() */
43 #include <pthread.h>
44 #include <sched.h>
46 #ifdef HAVE_EXECINFO_H
47 # include <execinfo.h>
48 #endif
49 #if defined(__SunOS)
50 # include <sys/processor.h>
51 # include <sys/pset.h>
52 #endif
54 static unsigned vlc_clock_prec;
56 static void vlc_clock_setup_once (void)
58 struct timespec res;
59 if (unlikely(clock_getres(CLOCK_MONOTONIC, &res) != 0 || res.tv_sec != 0))
60 abort ();
61 vlc_clock_prec = (res.tv_nsec + 500) / 1000;
64 /**
65 * Print a backtrace to the standard error for debugging purpose.
67 void vlc_trace (const char *fn, const char *file, unsigned line)
69 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
70 fflush (stderr); /* needed before switch to low-level I/O */
71 #ifdef HAVE_BACKTRACE
72 void *stack[20];
73 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
74 backtrace_symbols_fd (stack, len, 2);
75 #endif
76 fsync (2);
79 #ifndef NDEBUG
80 /**
81 * Reports a fatal error from the threading layer, for debugging purposes.
83 static void
84 vlc_thread_fatal (const char *action, int error,
85 const char *function, const char *file, unsigned line)
87 int canc = vlc_savecancel ();
88 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
89 action, error, vlc_thread_id ());
90 vlc_trace (function, file, line);
91 perror ("Thread error");
92 fflush (stderr);
94 vlc_restorecancel (canc);
95 abort ();
98 # define VLC_THREAD_ASSERT( action ) \
99 if (unlikely(val)) \
100 vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
101 #else
102 # define VLC_THREAD_ASSERT( action ) ((void)val)
103 #endif
105 void vlc_mutex_init( vlc_mutex_t *p_mutex )
107 pthread_mutexattr_t attr;
109 if (unlikely(pthread_mutexattr_init (&attr)))
110 abort();
111 #ifdef NDEBUG
112 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_DEFAULT);
113 #else
114 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK);
115 #endif
116 if (unlikely(pthread_mutex_init (p_mutex, &attr)))
117 abort();
118 pthread_mutexattr_destroy( &attr );
121 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
123 pthread_mutexattr_t attr;
125 if (unlikely(pthread_mutexattr_init (&attr)))
126 abort();
127 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
128 if (unlikely(pthread_mutex_init (p_mutex, &attr)))
129 abort();
130 pthread_mutexattr_destroy( &attr );
133 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
135 int val = pthread_mutex_destroy( p_mutex );
136 VLC_THREAD_ASSERT ("destroying mutex");
139 #ifndef NDEBUG
140 # ifdef HAVE_VALGRIND_VALGRIND_H
141 # include <valgrind/valgrind.h>
142 # else
143 # define RUNNING_ON_VALGRIND (0)
144 # endif
147 * Asserts that a mutex is locked by the calling thread.
149 void vlc_assert_locked (vlc_mutex_t *p_mutex)
151 if (RUNNING_ON_VALGRIND > 0)
152 return;
153 assert (pthread_mutex_lock (p_mutex) == EDEADLK);
155 #endif
157 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
159 int val = pthread_mutex_lock( p_mutex );
160 VLC_THREAD_ASSERT ("locking mutex");
163 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
165 int val = pthread_mutex_trylock( p_mutex );
167 if (val != EBUSY)
168 VLC_THREAD_ASSERT ("locking mutex");
169 return val;
172 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
174 int val = pthread_mutex_unlock( p_mutex );
175 VLC_THREAD_ASSERT ("unlocking mutex");
178 void vlc_cond_init (vlc_cond_t *p_condvar)
180 pthread_condattr_t attr;
182 if (unlikely(pthread_condattr_init (&attr))
183 || unlikely(pthread_condattr_setclock(&attr, CLOCK_MONOTONIC))
184 || unlikely(pthread_cond_init (p_condvar, &attr)))
185 abort ();
187 pthread_condattr_destroy (&attr);
190 void vlc_cond_init_daytime (vlc_cond_t *p_condvar)
192 if (unlikely(pthread_cond_init (p_condvar, NULL)))
193 abort ();
196 void vlc_cond_destroy (vlc_cond_t *p_condvar)
198 int val = pthread_cond_destroy( p_condvar );
199 VLC_THREAD_ASSERT ("destroying condition");
202 void vlc_cond_signal (vlc_cond_t *p_condvar)
204 int val = pthread_cond_signal( p_condvar );
205 VLC_THREAD_ASSERT ("signaling condition variable");
208 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
210 pthread_cond_broadcast (p_condvar);
213 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
215 int val = pthread_cond_wait( p_condvar, p_mutex );
216 VLC_THREAD_ASSERT ("waiting on condition");
219 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
220 vlc_tick_t deadline)
222 struct timespec ts = timespec_from_vlc_tick (deadline);
223 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
224 if (val != ETIMEDOUT)
225 VLC_THREAD_ASSERT ("timed-waiting on condition");
226 return val;
229 int vlc_cond_timedwait_daytime (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
230 time_t deadline)
232 struct timespec ts = { deadline, 0 };
233 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
234 if (val != ETIMEDOUT)
235 VLC_THREAD_ASSERT ("timed-waiting on condition");
236 return val;
239 void vlc_sem_init (vlc_sem_t *sem, unsigned value)
241 if (unlikely(sem_init (sem, 0, value)))
242 abort ();
245 void vlc_sem_destroy (vlc_sem_t *sem)
247 int val;
249 if (likely(sem_destroy (sem) == 0))
250 return;
252 val = errno;
254 VLC_THREAD_ASSERT ("destroying semaphore");
257 int vlc_sem_post (vlc_sem_t *sem)
259 int val;
261 if (likely(sem_post (sem) == 0))
262 return 0;
264 val = errno;
266 if (unlikely(val != EOVERFLOW))
267 VLC_THREAD_ASSERT ("unlocking semaphore");
268 return val;
271 void vlc_sem_wait (vlc_sem_t *sem)
273 int val;
276 if (likely(sem_wait (sem) == 0))
277 return;
278 while ((val = errno) == EINTR);
280 VLC_THREAD_ASSERT ("locking semaphore");
283 void vlc_rwlock_init (vlc_rwlock_t *lock)
285 if (unlikely(pthread_rwlock_init (lock, NULL)))
286 abort ();
289 void vlc_rwlock_destroy (vlc_rwlock_t *lock)
291 int val = pthread_rwlock_destroy (lock);
292 VLC_THREAD_ASSERT ("destroying R/W lock");
295 void vlc_rwlock_rdlock (vlc_rwlock_t *lock)
297 int val = pthread_rwlock_rdlock (lock);
298 VLC_THREAD_ASSERT ("acquiring R/W lock for reading");
301 void vlc_rwlock_wrlock (vlc_rwlock_t *lock)
303 int val = pthread_rwlock_wrlock (lock);
304 VLC_THREAD_ASSERT ("acquiring R/W lock for writing");
307 void vlc_rwlock_unlock (vlc_rwlock_t *lock)
309 int val = pthread_rwlock_unlock (lock);
310 VLC_THREAD_ASSERT ("releasing R/W lock");
313 void vlc_once(vlc_once_t *once, void (*cb)(void))
315 int val = pthread_once(once, cb);
316 VLC_THREAD_ASSERT("initializing once");
319 int vlc_threadvar_create (vlc_threadvar_t *key, void (*destr) (void *))
321 return pthread_key_create (key, destr);
324 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
326 pthread_key_delete (*p_tls);
329 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
331 return pthread_setspecific (key, value);
334 void *vlc_threadvar_get (vlc_threadvar_t key)
336 return pthread_getspecific (key);
339 static bool rt_priorities = false;
340 static int rt_offset;
342 void vlc_threads_setup (libvlc_int_t *p_libvlc)
344 static vlc_mutex_t lock = VLC_STATIC_MUTEX;
345 static bool initialized = false;
347 vlc_mutex_lock (&lock);
348 /* Initializes real-time priorities before any thread is created,
349 * just once per process. */
350 if (!initialized)
352 if (var_InheritBool (p_libvlc, "rt-priority"))
354 rt_offset = var_InheritInteger (p_libvlc, "rt-offset");
355 rt_priorities = true;
357 initialized = true;
359 vlc_mutex_unlock (&lock);
363 static int vlc_clone_attr (vlc_thread_t *th, pthread_attr_t *attr,
364 void *(*entry) (void *), void *data, int priority)
366 int ret;
368 /* Block the signals that signals interface plugin handles.
369 * If the LibVLC caller wants to handle some signals by itself, it should
370 * block these before whenever invoking LibVLC. And it must obviously not
371 * start the VLC signals interface plugin.
373 * LibVLC will normally ignore any interruption caused by an asynchronous
374 * signal during a system call. But there may well be some buggy cases
375 * where it fails to handle EINTR (bug reports welcome). Some underlying
376 * libraries might also not handle EINTR properly.
378 sigset_t oldset;
380 sigset_t set;
381 sigemptyset (&set);
382 sigdelset (&set, SIGHUP);
383 sigaddset (&set, SIGINT);
384 sigaddset (&set, SIGQUIT);
385 sigaddset (&set, SIGTERM);
387 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
388 pthread_sigmask (SIG_BLOCK, &set, &oldset);
391 #if defined (_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING >= 0) \
392 && defined (_POSIX_THREAD_PRIORITY_SCHEDULING) \
393 && (_POSIX_THREAD_PRIORITY_SCHEDULING >= 0)
394 if (rt_priorities)
396 struct sched_param sp = { .sched_priority = priority + rt_offset, };
397 int policy;
399 if (sp.sched_priority <= 0)
400 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
401 else
402 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
404 pthread_attr_setschedpolicy (attr, policy);
405 pthread_attr_setschedparam (attr, &sp);
406 pthread_attr_setinheritsched (attr, PTHREAD_EXPLICIT_SCHED);
408 #else
409 (void) priority;
410 #endif
412 /* The thread stack size.
413 * The lower the value, the less address space per thread, the highest
414 * maximum simultaneous threads per process. Too low values will cause
415 * stack overflows and weird crashes. Set with caution. Also keep in mind
416 * that 64-bits platforms consume more stack than 32-bits one.
418 * Thanks to on-demand paging, thread stack size only affects address space
419 * consumption. In terms of memory, threads only use what they need
420 * (rounded up to the page boundary).
422 * For example, on Linux i386, the default is 2 mega-bytes, which supports
423 * about 320 threads per processes. */
424 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
426 #ifdef VLC_STACKSIZE
427 ret = pthread_attr_setstacksize (attr, VLC_STACKSIZE);
428 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
429 #endif
431 ret = pthread_create(&th->handle, attr, entry, data);
432 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
433 pthread_attr_destroy (attr);
434 return ret;
437 int vlc_clone (vlc_thread_t *th, void *(*entry) (void *), void *data,
438 int priority)
440 pthread_attr_t attr;
442 pthread_attr_init (&attr);
443 return vlc_clone_attr (th, &attr, entry, data, priority);
446 void vlc_join(vlc_thread_t th, void **result)
448 int val = pthread_join(th.handle, result);
449 VLC_THREAD_ASSERT ("joining thread");
453 * Creates and starts new detached thread.
454 * A detached thread cannot be joined. Its resources will be automatically
455 * released whenever the thread exits (in particular, its call stack will be
456 * reclaimed).
458 * Detached thread are particularly useful when some work needs to be done
459 * asynchronously, that is likely to be completed much earlier than the thread
460 * can practically be joined. In this case, thread detach can spare memory.
462 * A detached thread may be cancelled, so as to expedite its termination.
463 * Be extremely careful if you do this: while a normal joinable thread can
464 * safely be cancelled after it has already exited, cancelling an already
465 * exited detached thread is undefined: The thread handle would is destroyed
466 * immediately when the detached thread exits. So you need to ensure that the
467 * detached thread is still running before cancellation is attempted.
469 * @warning Care must be taken that any resources used by the detached thread
470 * remains valid until the thread completes.
472 * @note A detached thread must eventually exit just like another other
473 * thread. In practice, LibVLC will wait for detached threads to exit before
474 * it unloads the plugins.
476 * @param th [OUT] pointer to hold the thread handle, or NULL
477 * @param entry entry point for the thread
478 * @param data data parameter given to the entry point
479 * @param priority thread priority value
480 * @return 0 on success, a standard error code on error.
482 int vlc_clone_detach (vlc_thread_t *th, void *(*entry) (void *), void *data,
483 int priority)
485 vlc_thread_t dummy;
486 pthread_attr_t attr;
488 if (th == NULL)
489 th = &dummy;
491 pthread_attr_init (&attr);
492 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
493 return vlc_clone_attr (th, &attr, entry, data, priority);
496 vlc_thread_t vlc_thread_self (void)
498 vlc_thread_t thread = { pthread_self() };
499 return thread;
502 VLC_WEAK unsigned long vlc_thread_id(void)
504 return -1;
507 int vlc_set_priority (vlc_thread_t th, int priority)
509 #if defined (_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING >= 0) \
510 && defined (_POSIX_THREAD_PRIORITY_SCHEDULING) \
511 && (_POSIX_THREAD_PRIORITY_SCHEDULING >= 0)
512 if (rt_priorities)
514 struct sched_param sp = { .sched_priority = priority + rt_offset, };
515 int policy;
517 if (sp.sched_priority <= 0)
518 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
519 else
520 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
522 if (pthread_setschedparam(th.handle, policy, &sp))
523 return VLC_EGENERIC;
525 #else
526 (void) th; (void) priority;
527 #endif
528 return VLC_SUCCESS;
531 void vlc_cancel(vlc_thread_t th)
533 pthread_cancel(th.handle);
536 int vlc_savecancel (void)
538 int state;
539 int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
541 VLC_THREAD_ASSERT ("saving cancellation");
542 return state;
545 void vlc_restorecancel (int state)
547 #ifndef NDEBUG
548 int oldstate, val;
550 val = pthread_setcancelstate (state, &oldstate);
551 /* This should fail if an invalid value for given for state */
552 VLC_THREAD_ASSERT ("restoring cancellation");
554 if (unlikely(oldstate != PTHREAD_CANCEL_DISABLE))
555 vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
556 __func__, __FILE__, __LINE__);
557 #else
558 pthread_setcancelstate (state, NULL);
559 #endif
562 void vlc_testcancel (void)
564 pthread_testcancel ();
567 void vlc_control_cancel (int cmd, ...)
569 (void) cmd;
570 vlc_assert_unreachable ();
573 vlc_tick_t vlc_tick_now (void)
575 struct timespec ts;
577 if (unlikely(clock_gettime(CLOCK_MONOTONIC, &ts) != 0))
578 abort ();
580 return vlc_tick_from_timespec( &ts );
583 #undef vlc_tick_wait
584 void vlc_tick_wait (vlc_tick_t deadline)
586 static pthread_once_t vlc_clock_once = PTHREAD_ONCE_INIT;
588 /* If the deadline is already elapsed, or within the clock precision,
589 * do not even bother the system timer. */
590 pthread_once(&vlc_clock_once, vlc_clock_setup_once);
591 deadline -= vlc_clock_prec;
593 struct timespec ts = timespec_from_vlc_tick (deadline);
595 while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR);
598 #undef vlc_tick_sleep
599 void vlc_tick_sleep (vlc_tick_t delay)
601 struct timespec ts = timespec_from_vlc_tick (delay);
603 while (clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, &ts) == EINTR);
606 unsigned vlc_GetCPUCount(void)
608 #if defined(HAVE_SCHED_GETAFFINITY)
609 cpu_set_t cpu;
611 CPU_ZERO(&cpu);
612 if (sched_getaffinity (0, sizeof (cpu), &cpu) < 0)
613 return 1;
615 return CPU_COUNT (&cpu);
617 #elif defined(__SunOS)
618 unsigned count = 0;
619 int type;
620 u_int numcpus;
621 processor_info_t cpuinfo;
623 processorid_t *cpulist = vlc_alloc (sysconf(_SC_NPROCESSORS_MAX), sizeof (*cpulist));
624 if (unlikely(cpulist == NULL))
625 return 1;
627 if (pset_info(PS_MYID, &type, &numcpus, cpulist) == 0)
629 for (u_int i = 0; i < numcpus; i++)
630 if (processor_info (cpulist[i], &cpuinfo) == 0)
631 count += (cpuinfo.pi_state == P_ONLINE);
633 else
634 count = sysconf (_SC_NPROCESSORS_ONLN);
635 free (cpulist);
636 return count ? count : 1;
637 #elif defined(_SC_NPROCESSORS_CONF)
638 return sysconf(_SC_NPROCESSORS_CONF);
639 #else
640 # warning "vlc_GetCPUCount is not implemented for your platform"
641 return 1;
642 #endif