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>
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 *****************************************************************************/
31 #include <vlc_common.h>
35 #include <stdatomic.h>
41 #include <sys/types.h>
42 #include <unistd.h> /* fsync() */
46 #ifdef HAVE_EXECINFO_H
47 # include <execinfo.h>
50 # include <sys/processor.h>
51 # include <sys/pset.h>
54 static unsigned vlc_clock_prec
;
56 static void vlc_clock_setup_once (void)
59 if (unlikely(clock_getres(CLOCK_MONOTONIC
, &res
) != 0 || res
.tv_sec
!= 0))
61 vlc_clock_prec
= (res
.tv_nsec
+ 500) / 1000;
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 */
73 int len
= backtrace (stack
, sizeof (stack
) / sizeof (stack
[0]));
74 backtrace_symbols_fd (stack
, len
, 2);
81 * Reports a fatal error from the threading layer, for debugging purposes.
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");
94 vlc_restorecancel (canc
);
98 # define VLC_THREAD_ASSERT( action ) \
100 vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
102 # define VLC_THREAD_ASSERT( action ) ((void)val)
105 void vlc_mutex_init( vlc_mutex_t
*p_mutex
)
107 pthread_mutexattr_t attr
;
109 if (unlikely(pthread_mutexattr_init (&attr
)))
112 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_DEFAULT
);
114 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_ERRORCHECK
);
116 if (unlikely(pthread_mutex_init (p_mutex
, &attr
)))
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
)))
127 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
128 if (unlikely(pthread_mutex_init (p_mutex
, &attr
)))
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");
140 # ifdef HAVE_VALGRIND_VALGRIND_H
141 # include <valgrind/valgrind.h>
143 # define RUNNING_ON_VALGRIND (0)
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)
153 assert (pthread_mutex_lock (p_mutex
) == EDEADLK
);
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
);
168 VLC_THREAD_ASSERT ("locking mutex");
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
)))
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
)))
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
,
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");
229 int vlc_cond_timedwait_daytime (vlc_cond_t
*p_condvar
, vlc_mutex_t
*p_mutex
,
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");
239 void vlc_sem_init (vlc_sem_t
*sem
, unsigned value
)
241 if (unlikely(sem_init (sem
, 0, value
)))
245 void vlc_sem_destroy (vlc_sem_t
*sem
)
249 if (likely(sem_destroy (sem
) == 0))
254 VLC_THREAD_ASSERT ("destroying semaphore");
257 int vlc_sem_post (vlc_sem_t
*sem
)
261 if (likely(sem_post (sem
) == 0))
266 if (unlikely(val
!= EOVERFLOW
))
267 VLC_THREAD_ASSERT ("unlocking semaphore");
271 void vlc_sem_wait (vlc_sem_t
*sem
)
276 if (likely(sem_wait (sem
) == 0))
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
)))
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. */
352 if (var_InheritBool (p_libvlc
, "rt-priority"))
354 rt_offset
= var_InheritInteger (p_libvlc
, "rt-offset");
355 rt_priorities
= 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
)
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.
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)
396 struct sched_param sp
= { .sched_priority
= priority
+ rt_offset
, };
399 if (sp
.sched_priority
<= 0)
400 sp
.sched_priority
+= sched_get_priority_max (policy
= SCHED_OTHER
);
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
);
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)
427 ret
= pthread_attr_setstacksize (attr
, VLC_STACKSIZE
);
428 assert (ret
== 0); /* fails iif VLC_STACKSIZE is invalid */
431 ret
= pthread_create(&th
->handle
, attr
, entry
, data
);
432 pthread_sigmask (SIG_SETMASK
, &oldset
, NULL
);
433 pthread_attr_destroy (attr
);
437 int vlc_clone (vlc_thread_t
*th
, void *(*entry
) (void *), void *data
,
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
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
,
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() };
502 VLC_WEAK
unsigned long vlc_thread_id(void)
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)
514 struct sched_param sp
= { .sched_priority
= priority
+ rt_offset
, };
517 if (sp
.sched_priority
<= 0)
518 sp
.sched_priority
+= sched_get_priority_max (policy
= SCHED_OTHER
);
520 sp
.sched_priority
+= sched_get_priority_min (policy
= SCHED_RR
);
522 if (pthread_setschedparam(th
.handle
, policy
, &sp
))
526 (void) th
; (void) priority
;
531 void vlc_cancel(vlc_thread_t th
)
533 pthread_cancel(th
.handle
);
536 int vlc_savecancel (void)
539 int val
= pthread_setcancelstate (PTHREAD_CANCEL_DISABLE
, &state
);
541 VLC_THREAD_ASSERT ("saving cancellation");
545 void vlc_restorecancel (int state
)
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__
);
558 pthread_setcancelstate (state
, NULL
);
562 void vlc_testcancel (void)
564 pthread_testcancel ();
567 void vlc_control_cancel (int cmd
, ...)
570 vlc_assert_unreachable ();
573 vlc_tick_t
vlc_tick_now (void)
577 if (unlikely(clock_gettime(CLOCK_MONOTONIC
, &ts
) != 0))
580 return vlc_tick_from_timespec( &ts
);
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)
612 if (sched_getaffinity (0, sizeof (cpu
), &cpu
) < 0)
615 return CPU_COUNT (&cpu
);
617 #elif defined(__SunOS)
621 processor_info_t cpuinfo
;
623 processorid_t
*cpulist
= vlc_alloc (sysconf(_SC_NPROCESSORS_MAX
), sizeof (*cpulist
));
624 if (unlikely(cpulist
== NULL
))
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
);
634 count
= sysconf (_SC_NPROCESSORS_ONLN
);
636 return count
? count
: 1;
637 #elif defined(_SC_NPROCESSORS_CONF)
638 return sysconf(_SC_NPROCESSORS_CONF
);
640 # warning "vlc_GetCPUCount is not implemented for your platform"