1 /*****************************************************************************
2 * threads.c : threads implementation for the VideoLAN client
3 *****************************************************************************
4 * Copyright (C) 1999-2008 the VideoLAN team
7 * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
8 * Samuel Hocevar <sam@zoy.org>
9 * Gildas Bazin <gbazin@netcourrier.com>
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26 *****************************************************************************/
32 #include <vlc_common.h>
42 #if defined( LIBVLC_USE_PTHREAD )
45 # include <sys/syscall.h> /* SYS_gettid */
48 static vlc_threadvar_t cancel_key;
51 #ifdef HAVE_EXECINFO_H
52 # include <execinfo.h>
56 # include <sys/time.h> /* gettimeofday in vlc_cond_timedwait */
60 * Print a backtrace to the standard error for debugging purpose.
62 void vlc_trace (const char *fn, const char *file, unsigned line)
64 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
65 fflush (stderr); /* needed before switch to low-level I/O */
68 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
69 backtrace_symbols_fd (stack, len, 2);
76 static inline unsigned long vlc_threadid (void)
78 #if defined (LIBVLC_USE_PTHREAD)
79 # if defined (__linux__)
80 return syscall (SYS_gettid);
83 union { pthread_t th; unsigned long int i; } v = { };
84 v.th = pthread_self ();
89 return GetCurrentThreadId ();
98 /*****************************************************************************
99 * vlc_thread_fatal: Report an error from the threading layer
100 *****************************************************************************
101 * This is mostly meant for debugging.
102 *****************************************************************************/
104 vlc_thread_fatal (const char *action, int error,
105 const char *function, const char *file, unsigned line)
107 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
108 action, error, vlc_threadid ());
109 vlc_trace (function, file, line);
111 /* Sometimes strerror_r() crashes too, so make sure we print an error
112 * message before we invoke it */
114 /* Avoid the strerror_r() prototype brain damage in glibc */
116 fprintf (stderr, " Error message: %m\n");
117 #elif !defined (WIN32)
121 switch (strerror_r (error, buf, sizeof (buf)))
126 case ERANGE: /* should never happen */
127 msg = "unknwon (too big to display)";
130 msg = "unknown (invalid error number)";
133 fprintf (stderr, " Error message: %s\n", msg);
140 # define VLC_THREAD_ASSERT( action ) \
141 if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
143 # define VLC_THREAD_ASSERT( action ) ((void)val)
147 * Per-thread cancellation data
149 #ifndef LIBVLC_USE_PTHREAD_CANCEL
150 typedef struct vlc_cancel_t
152 vlc_cleanup_t *cleaners;
161 # define VLC_CANCEL_INIT { NULL, true, false }
163 # define VLC_CANCEL_INIT { NULL, true, false, NULL }
168 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy);
170 static DWORD vlc_cancelable_wait (DWORD count, const HANDLE *handles,
173 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
176 /* Main thread - cannot be cancelled anyway */
177 return WaitForMultipleObjects (count, handles, FALSE, delay);
179 HANDLE new_handles[count + 1];
180 memcpy(new_handles, handles, count * sizeof(HANDLE));
181 new_handles[count] = nfo->cancel_event;
182 DWORD result = WaitForMultipleObjects (count + 1, new_handles, FALSE,
184 if (result == WAIT_OBJECT_0 + count)
186 vlc_cancel_self (NULL);
187 return WAIT_IO_COMPLETION;
195 DWORD SleepEx (DWORD dwMilliseconds, BOOL bAlertable)
199 DWORD result = vlc_cancelable_wait (0, NULL, dwMilliseconds);
200 return (result == WAIT_TIMEOUT) ? 0 : WAIT_IO_COMPLETION;
204 Sleep(dwMilliseconds);
209 DWORD WaitForSingleObjectEx (HANDLE hHandle, DWORD dwMilliseconds,
214 /* The MSDN documentation specifies different return codes,
215 * but in practice they are the same. We just check that it
217 #if WAIT_ABANDONED != WAIT_ABANDONED_0
218 # error Windows headers changed, code needs to be rewritten!
220 return vlc_cancelable_wait (1, &hHandle, dwMilliseconds);
224 return WaitForSingleObject (hHandle, dwMilliseconds);
228 DWORD WaitForMultipleObjectsEx (DWORD nCount, const HANDLE *lpHandles,
229 BOOL bWaitAll, DWORD dwMilliseconds,
234 /* We do not support the bWaitAll case */
236 return vlc_cancelable_wait (nCount, lpHandles, dwMilliseconds);
240 return WaitForMultipleObjects (nCount, lpHandles, bWaitAll,
247 static vlc_mutex_t super_mutex, tls_mutex;
248 static struct vlc_threadvar *tls_list = NULL;
250 BOOL WINAPI DllMain (HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvReserved)
257 case DLL_PROCESS_ATTACH:
258 vlc_mutex_init (&super_mutex);
259 vlc_mutex_init (&tls_mutex);
260 vlc_threadvar_create (&cancel_key, free);
263 case DLL_PROCESS_DETACH:
264 vlc_threadvar_delete( &cancel_key );
265 assert (tls_list == NULL);
266 vlc_mutex_destroy (&tls_mutex);
267 vlc_mutex_destroy (&super_mutex);
274 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
275 /* This is not prototyped under glibc, though it exists. */
276 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
279 /*****************************************************************************
280 * vlc_mutex_init: initialize a mutex
281 *****************************************************************************/
282 int vlc_mutex_init( vlc_mutex_t *p_mutex )
284 #if defined( LIBVLC_USE_PTHREAD )
285 pthread_mutexattr_t attr;
288 pthread_mutexattr_init( &attr );
291 /* Create error-checking mutex to detect problems more easily. */
292 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
293 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
295 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
298 i_result = pthread_mutex_init( p_mutex, &attr );
299 pthread_mutexattr_destroy( &attr );
302 #elif defined( WIN32 )
303 /* This creates a recursive mutex. This is OK as fast mutexes have
304 * no defined behavior in case of recursive locking. */
305 InitializeCriticalSection (&p_mutex->mutex);
306 p_mutex->initialized = 1;
312 /*****************************************************************************
313 * vlc_mutex_init: initialize a recursive mutex (Do not use)
314 *****************************************************************************/
315 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
317 #if defined( LIBVLC_USE_PTHREAD )
318 pthread_mutexattr_t attr;
321 pthread_mutexattr_init( &attr );
322 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
323 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
325 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
327 i_result = pthread_mutex_init( p_mutex, &attr );
328 pthread_mutexattr_destroy( &attr );
331 #elif defined( WIN32 )
332 InitializeCriticalSection( &p_mutex->mutex );
333 p_mutex->initialized = 1;
341 * Destroys a mutex. The mutex must not be locked.
343 * @param p_mutex mutex to destroy
344 * @return always succeeds
346 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
348 #if defined( LIBVLC_USE_PTHREAD )
349 int val = pthread_mutex_destroy( p_mutex );
350 VLC_THREAD_ASSERT ("destroying mutex");
352 #elif defined( WIN32 )
353 assert (InterlockedExchange (&p_mutex->initialized, -1) == 1);
354 DeleteCriticalSection (&p_mutex->mutex);
359 #if defined(LIBVLC_USE_PTHREAD) && !defined(NDEBUG)
360 void vlc_assert_locked (vlc_mutex_t *p_mutex)
362 assert (pthread_mutex_lock (p_mutex) == EDEADLK);
367 * Acquires a mutex. If needed, waits for any other thread to release it.
368 * Beware of deadlocks when locking multiple mutexes at the same time,
369 * or when using mutexes from callbacks.
370 * This function is not a cancellation-point.
372 * @param p_mutex mutex initialized with vlc_mutex_init() or
373 * vlc_mutex_init_recursive()
375 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
377 #if defined(LIBVLC_USE_PTHREAD)
378 int val = pthread_mutex_lock( p_mutex );
379 VLC_THREAD_ASSERT ("locking mutex");
381 #elif defined( WIN32 )
382 if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
383 { /* ^^ We could also lock super_mutex all the time... sluggish */
384 assert (p_mutex != &super_mutex); /* this one cannot be static */
386 vlc_mutex_lock (&super_mutex);
387 if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
388 vlc_mutex_init (p_mutex);
389 /* FIXME: destroy the mutex some time... */
390 vlc_mutex_unlock (&super_mutex);
392 assert (InterlockedExchange (&p_mutex->initialized, 1) == 1);
393 EnterCriticalSection (&p_mutex->mutex);
399 * Acquires a mutex if and only if it is not currently held by another thread.
400 * This function never sleeps and can be used in delay-critical code paths.
401 * This function is not a cancellation-point.
403 * <b>Beware</b>: If this function fails, then the mutex is held... by another
404 * thread. The calling thread must deal with the error appropriately. That
405 * typically implies postponing the operations that would have required the
406 * mutex. If the thread cannot defer those operations, then it must use
407 * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
409 * @param p_mutex mutex initialized with vlc_mutex_init() or
410 * vlc_mutex_init_recursive()
411 * @return 0 if the mutex could be acquired, an error code otherwise.
413 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
415 #if defined(LIBVLC_USE_PTHREAD)
416 int val = pthread_mutex_trylock( p_mutex );
419 VLC_THREAD_ASSERT ("locking mutex");
422 #elif defined( WIN32 )
423 if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
424 { /* ^^ We could also lock super_mutex all the time... sluggish */
425 assert (p_mutex != &super_mutex); /* this one cannot be static */
427 vlc_mutex_lock (&super_mutex);
428 if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
429 vlc_mutex_init (p_mutex);
430 /* FIXME: destroy the mutex some time... */
431 vlc_mutex_unlock (&super_mutex);
433 assert (InterlockedExchange (&p_mutex->initialized, 1) == 1);
434 return TryEnterCriticalSection (&p_mutex->mutex) ? 0 : EBUSY;
440 * Releases a mutex (or crashes if the mutex is not locked by the caller).
441 * @param p_mutex mutex locked with vlc_mutex_lock().
443 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
445 #if defined(LIBVLC_USE_PTHREAD)
446 int val = pthread_mutex_unlock( p_mutex );
447 VLC_THREAD_ASSERT ("unlocking mutex");
449 #elif defined( WIN32 )
450 assert (InterlockedExchange (&p_mutex->initialized, 1) == 1);
451 LeaveCriticalSection (&p_mutex->mutex);
456 /*****************************************************************************
457 * vlc_cond_init: initialize a condition variable
458 *****************************************************************************/
459 int vlc_cond_init( vlc_cond_t *p_condvar )
461 #if defined( LIBVLC_USE_PTHREAD )
462 pthread_condattr_t attr;
465 ret = pthread_condattr_init (&attr);
469 # if !defined (_POSIX_CLOCK_SELECTION)
470 /* Fairly outdated POSIX support (that was defined in 2001) */
471 # define _POSIX_CLOCK_SELECTION (-1)
473 # if (_POSIX_CLOCK_SELECTION >= 0)
474 /* NOTE: This must be the same clock as the one in mtime.c */
475 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
478 ret = pthread_cond_init (p_condvar, &attr);
479 pthread_condattr_destroy (&attr);
482 #elif defined( WIN32 )
483 /* Create a manual-reset event (manual reset is needed for broadcast). */
484 *p_condvar = CreateEvent( NULL, TRUE, FALSE, NULL );
485 return *p_condvar ? 0 : ENOMEM;
491 * Destroys a condition variable. No threads shall be waiting or signaling the
493 * @param p_condvar condition variable to destroy
495 void vlc_cond_destroy (vlc_cond_t *p_condvar)
497 #if defined( LIBVLC_USE_PTHREAD )
498 int val = pthread_cond_destroy( p_condvar );
499 VLC_THREAD_ASSERT ("destroying condition");
501 #elif defined( WIN32 )
502 CloseHandle( *p_condvar );
508 * Wakes up one thread waiting on a condition variable, if any.
509 * @param p_condvar condition variable
511 void vlc_cond_signal (vlc_cond_t *p_condvar)
513 #if defined(LIBVLC_USE_PTHREAD)
514 int val = pthread_cond_signal( p_condvar );
515 VLC_THREAD_ASSERT ("signaling condition variable");
517 #elif defined( WIN32 )
518 /* NOTE: This will cause a broadcast, that is wrong.
519 * This will also wake up the next waiting thread if no thread are yet
520 * waiting, which is also wrong. However both of these issues are allowed
521 * by the provision for spurious wakeups. Better have too many wakeups
522 * than too few (= deadlocks). */
523 SetEvent (*p_condvar);
529 * Wakes up all threads (if any) waiting on a condition variable.
530 * @param p_cond condition variable
532 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
534 #if defined (LIBVLC_USE_PTHREAD)
535 pthread_cond_broadcast (p_condvar);
537 #elif defined (WIN32)
538 SetEvent (*p_condvar);
544 * Waits for a condition variable. The calling thread will be suspended until
545 * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
546 * condition variable, the thread is cancelled with vlc_cancel(), or the
547 * system causes a "spurious" unsolicited wake-up.
549 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
550 * a recursive mutex. Although it is possible to use the same mutex for
551 * multiple condition, it is not valid to use different mutexes for the same
552 * condition variable at the same time from different threads.
554 * In case of thread cancellation, the mutex is always locked before
555 * cancellation proceeds.
557 * The canonical way to use a condition variable to wait for event foobar is:
559 vlc_mutex_lock (&lock);
560 mutex_cleanup_push (&lock); // release the mutex in case of cancellation
563 vlc_cond_wait (&wait, &lock);
565 --- foobar is now true, do something about it here --
567 vlc_cleanup_run (); // release the mutex
570 * @param p_condvar condition variable to wait on
571 * @param p_mutex mutex which is unlocked while waiting,
572 * then locked again when waking up.
573 * @param deadline <b>absolute</b> timeout
575 * @return 0 if the condition was signaled, an error code in case of timeout.
577 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
579 #if defined(LIBVLC_USE_PTHREAD)
580 int val = pthread_cond_wait( p_condvar, p_mutex );
581 VLC_THREAD_ASSERT ("waiting on condition");
583 #elif defined( WIN32 )
589 LeaveCriticalSection (&p_mutex->mutex);
590 result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
591 EnterCriticalSection (&p_mutex->mutex);
593 while (result == WAIT_IO_COMPLETION);
595 ResetEvent (*p_condvar);
601 * Waits for a condition variable up to a certain date.
602 * This works like vlc_cond_wait(), except for the additional timeout.
604 * @param p_condvar condition variable to wait on
605 * @param p_mutex mutex which is unlocked while waiting,
606 * then locked again when waking up.
607 * @param deadline <b>absolute</b> timeout
609 * @return 0 if the condition was signaled, an error code in case of timeout.
611 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
614 #if defined(LIBVLC_USE_PTHREAD)
616 /* mdate() is mac_absolute_time on osx, which we must convert to do
617 * the same base than gettimeofday() on which pthread_cond_timedwait
619 mtime_t oldbase = mdate();
621 gettimeofday(&tv, NULL);
622 mtime_t newbase = (mtime_t)tv.tv_sec * 1000000 + (mtime_t) tv.tv_usec;
623 deadline = deadline - oldbase + newbase;
625 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
626 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
628 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
629 if (val != ETIMEDOUT)
630 VLC_THREAD_ASSERT ("timed-waiting on condition");
633 #elif defined( WIN32 )
640 mtime_t total = (deadline - mdate ())/1000;
644 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
645 LeaveCriticalSection (&p_mutex->mutex);
646 result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
647 EnterCriticalSection (&p_mutex->mutex);
649 while (result == WAIT_IO_COMPLETION);
651 ResetEvent (*p_condvar);
653 return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
659 #if defined (LIBVLC_USE_PTHREAD)
660 #elif defined (WIN32)
664 void (*cleanup) (void *);
665 struct vlc_threadvar *prev, *next;
668 static void vlc_threadvar_cleanup (void)
670 struct vlc_threadvar *p;
672 vlc_mutex_lock (&tls_mutex);
673 for (p = tls_list; p != NULL; p = p->next)
675 void *value = TlsGetValue (p->handle);
679 vlc_mutex_unlock (&tls_mutex);
683 /*****************************************************************************
684 * vlc_tls_create: create a thread-local variable
685 *****************************************************************************/
686 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
688 #if defined( LIBVLC_USE_PTHREAD )
689 return pthread_key_create( p_tls, destr );
691 #elif defined( WIN32 )
692 struct vlc_threadvar *tls = malloc (sizeof (*tls));
696 tls->handle = TlsAlloc();
697 if (tls->handle == TLS_OUT_OF_INDEXES)
702 tls->cleanup = destr;
704 vlc_mutex_lock (&tls_mutex);
705 tls->next = tls_list;
707 tls_list->prev = tls;
709 vlc_mutex_unlock (&tls_mutex);
714 # error Unimplemented!
718 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
720 #if defined( LIBVLC_USE_PTHREAD )
721 pthread_key_delete (*p_tls);
723 #elif defined( WIN32 )
724 struct vlc_threadvar *tls = *p_tls;
726 TlsFree (tls->handle);
727 vlc_mutex_lock (&tls_mutex);
729 tls->prev->next = tls->next;
731 tls->next->prev = tls->prev;
732 vlc_mutex_unlock (&tls_mutex);
736 # error Unimplemented!
741 * Sets a thread-local variable.
742 * @param key thread-local variable key (created with vlc_threadvar_create())
743 * @param value new value for the variable for the calling thread
744 * @return 0 on success, a system error code otherwise.
746 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
748 #if defined(LIBVLC_USE_PTHREAD)
749 return pthread_setspecific (key, value);
750 #elif defined( UNDER_CE ) || defined( WIN32 )
751 return TlsSetValue (key->handle, value) ? ENOMEM : 0;
753 # error Unimplemented!
758 * Gets the value of a thread-local variable for the calling thread.
759 * This function cannot fail.
760 * @return the value associated with the given variable for the calling
761 * or NULL if there is no value.
763 void *vlc_threadvar_get (vlc_threadvar_t key)
765 #if defined(LIBVLC_USE_PTHREAD)
766 return pthread_getspecific (key);
767 #elif defined( UNDER_CE ) || defined( WIN32 )
768 return TlsGetValue (key->handle);
770 # error Unimplemented!
774 #if defined (LIBVLC_USE_PTHREAD)
775 #elif defined (WIN32)
776 static unsigned __stdcall vlc_entry (void *data)
778 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
779 vlc_thread_t self = data;
781 cancel_data.cancel_event = self->cancel_event;
784 vlc_threadvar_set (cancel_key, &cancel_data);
785 self->data = self->entry (self->data);
786 vlc_threadvar_cleanup ();
792 * Creates and starts new thread.
794 * @param p_handle [OUT] pointer to write the handle of the created thread to
795 * @param entry entry point for the thread
796 * @param data data parameter given to the entry point
797 * @param priority thread priority value
798 * @return 0 on success, a standard error code on error.
800 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
805 #if defined( LIBVLC_USE_PTHREAD )
807 pthread_attr_init (&attr);
809 /* Block the signals that signals interface plugin handles.
810 * If the LibVLC caller wants to handle some signals by itself, it should
811 * block these before whenever invoking LibVLC. And it must obviously not
812 * start the VLC signals interface plugin.
814 * LibVLC will normally ignore any interruption caused by an asynchronous
815 * signal during a system call. But there may well be some buggy cases
816 * where it fails to handle EINTR (bug reports welcome). Some underlying
817 * libraries might also not handle EINTR properly.
823 sigdelset (&set, SIGHUP);
824 sigaddset (&set, SIGINT);
825 sigaddset (&set, SIGQUIT);
826 sigaddset (&set, SIGTERM);
828 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
829 pthread_sigmask (SIG_BLOCK, &set, &oldset);
832 struct sched_param sp = { .sched_priority = priority, };
835 if (sp.sched_priority <= 0)
836 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
838 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
840 pthread_attr_setschedpolicy (&attr, policy);
841 pthread_attr_setschedparam (&attr, &sp);
844 /* The thread stack size.
845 * The lower the value, the less address space per thread, the highest
846 * maximum simultaneous threads per process. Too low values will cause
847 * stack overflows and weird crashes. Set with caution. Also keep in mind
848 * that 64-bits platforms consume more stack than 32-bits one.
850 * Thanks to on-demand paging, thread stack size only affects address space
851 * consumption. In terms of memory, threads only use what they need
852 * (rounded up to the page boundary).
854 * For example, on Linux i386, the default is 2 mega-bytes, which supports
855 * about 320 threads per processes. */
856 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
859 ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
860 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
863 ret = pthread_create (p_handle, &attr, entry, data);
864 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
865 pthread_attr_destroy (&attr);
867 #elif defined( WIN32 ) || defined( UNDER_CE )
868 /* When using the MSVCRT C library you have to use the _beginthreadex
869 * function instead of CreateThread, otherwise you'll end up with
870 * memory leaks and the signal functions not working (see Microsoft
871 * Knowledge Base, article 104641) */
873 vlc_thread_t th = malloc (sizeof (*th));
880 #if defined( UNDER_CE )
881 th->cancel_event = CreateEvent (NULL, FALSE, FALSE, NULL);
882 if (th->cancel_event == NULL)
887 hThread = CreateThread (NULL, 128*1024, vlc_entry, th, CREATE_SUSPENDED, NULL);
889 hThread = (HANDLE)(uintptr_t)
890 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
896 /* Thread closes the handle when exiting, duplicate it here
897 * to be on the safe side when joining. */
898 if (!DuplicateHandle (GetCurrentProcess (), hThread,
899 GetCurrentProcess (), &th->handle, 0, FALSE,
900 DUPLICATE_SAME_ACCESS))
902 CloseHandle (hThread);
907 th->handle = hThread;
910 ResumeThread (hThread);
912 SetThreadPriority (hThread, priority);
928 /* APC procedure for thread cancellation */
929 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
932 vlc_control_cancel (VLC_DO_CANCEL);
937 * Marks a thread as cancelled. Next time the target thread reaches a
938 * cancellation point (while not having disabled cancellation), it will
939 * run its cancellation cleanup handler, the thread variable destructors, and
940 * terminate. vlc_join() must be used afterward regardless of a thread being
943 void vlc_cancel (vlc_thread_t thread_id)
945 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
946 pthread_cancel (thread_id);
947 #elif defined (UNDER_CE)
948 SetEvent (thread_id->cancel_event);
949 #elif defined (WIN32)
950 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
952 # warning vlc_cancel is not implemented!
957 * Waits for a thread to complete (if needed), and destroys it.
958 * This is a cancellation point; in case of cancellation, the join does _not_
961 * @param handle thread handle
962 * @param p_result [OUT] pointer to write the thread return value or NULL
963 * @return 0 on success, a standard error code otherwise.
965 void vlc_join (vlc_thread_t handle, void **result)
967 #if defined( LIBVLC_USE_PTHREAD )
968 int val = pthread_join (handle, result);
969 VLC_THREAD_ASSERT ("joining thread");
971 #elif defined( UNDER_CE ) || defined( WIN32 )
974 while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
975 == WAIT_IO_COMPLETION);
977 CloseHandle (handle->handle);
979 *result = handle->data;
980 #if defined( UNDER_CE )
981 CloseHandle (handle->cancel_event);
989 * Save the current cancellation state (enabled or disabled), then disable
990 * cancellation for the calling thread.
991 * This function must be called before entering a piece of code that is not
992 * cancellation-safe, unless it can be proven that the calling thread will not
994 * @return Previous cancellation state (opaque value for vlc_restorecancel()).
996 int vlc_savecancel (void)
1000 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
1001 int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
1002 VLC_THREAD_ASSERT ("saving cancellation");
1005 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
1007 return false; /* Main thread - cannot be cancelled anyway */
1009 state = nfo->killable;
1010 nfo->killable = false;
1017 * Restore the cancellation state for the calling thread.
1018 * @param state previous state as returned by vlc_savecancel().
1019 * @return Nothing, always succeeds.
1021 void vlc_restorecancel (int state)
1023 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
1027 val = pthread_setcancelstate (state, &oldstate);
1028 /* This should fail if an invalid value for given for state */
1029 VLC_THREAD_ASSERT ("restoring cancellation");
1031 if (oldstate != PTHREAD_CANCEL_DISABLE)
1032 vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
1033 __func__, __FILE__, __LINE__);
1035 pthread_setcancelstate (state, NULL);
1039 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
1040 assert (state == false || state == true);
1043 return; /* Main thread - cannot be cancelled anyway */
1045 assert (!nfo->killable);
1046 nfo->killable = state != 0;
1052 * Issues an explicit deferred cancellation point.
1053 * This has no effect if thread cancellation is disabled.
1054 * This can be called when there is a rather slow non-sleeping operation.
1055 * This is also used to force a cancellation point in a function that would
1056 * otherwise "not always" be a one (block_FifoGet() is an example).
1058 void vlc_testcancel (void)
1060 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
1061 pthread_testcancel ();
1064 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
1066 return; /* Main thread - cannot be cancelled anyway */
1068 if (nfo->killable && nfo->killed)
1070 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
1072 # if defined (LIBVLC_USE_PTHREAD)
1073 pthread_exit (PTHREAD_CANCELLED);
1074 # elif defined (UNDER_CE)
1075 vlc_threadvar_cleanup ();
1077 # elif defined (WIN32)
1078 vlc_threadvar_cleanup ();
1081 # error Not implemented!
1088 struct vlc_thread_boot
1090 void * (*entry) (vlc_object_t *);
1091 vlc_object_t *object;
1094 static void *thread_entry (void *data)
1096 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
1097 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
1100 msg_Dbg (obj, "thread started");
1102 msg_Dbg (obj, "thread ended");
1107 #undef vlc_thread_create
1108 /*****************************************************************************
1109 * vlc_thread_create: create a thread
1110 *****************************************************************************
1111 * Note that i_priority is only taken into account on platforms supporting
1112 * userland real-time priority threads.
1113 *****************************************************************************/
1114 int vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
1115 const char *psz_name, void *(*func) ( vlc_object_t * ),
1119 vlc_object_internals_t *p_priv = vlc_internals( p_this );
1121 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
1125 boot->object = p_this;
1127 /* Make sure we don't re-create a thread if the object has already one */
1128 assert( !p_priv->b_thread );
1130 #if defined( LIBVLC_USE_PTHREAD )
1132 if( config_GetInt( p_this, "rt-priority" ) > 0 )
1135 /* Hack to avoid error msg */
1136 if( config_GetType( p_this, "rt-offset" ) )
1137 i_priority += config_GetInt( p_this, "rt-offset" );
1141 p_priv->b_thread = true;
1142 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
1144 msg_Dbg( p_this, "thread (%s) created at priority %d (%s:%d)",
1145 psz_name, i_priority, psz_file, i_line );
1148 p_priv->b_thread = false;
1150 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
1151 psz_name, psz_file, i_line );
1157 /*****************************************************************************
1158 * vlc_thread_set_priority: set the priority of the current thread when we
1159 * couldn't set it in vlc_thread_create (for instance for the main thread)
1160 *****************************************************************************/
1161 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
1162 int i_line, int i_priority )
1164 vlc_object_internals_t *p_priv = vlc_internals( p_this );
1166 if( !p_priv->b_thread )
1168 msg_Err( p_this, "couldn't set priority of non-existent thread" );
1172 #if defined( LIBVLC_USE_PTHREAD )
1174 if( config_GetInt( p_this, "rt-priority" ) > 0 )
1177 int i_error, i_policy;
1178 struct sched_param param;
1180 memset( ¶m, 0, sizeof(struct sched_param) );
1181 if( config_GetType( p_this, "rt-offset" ) )
1182 i_priority += config_GetInt( p_this, "rt-offset" );
1183 if( i_priority <= 0 )
1185 param.sched_priority = (-1) * i_priority;
1186 i_policy = SCHED_OTHER;
1190 param.sched_priority = i_priority;
1191 i_policy = SCHED_RR;
1193 if( (i_error = pthread_setschedparam( p_priv->thread_id,
1194 i_policy, ¶m )) )
1197 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
1203 #elif defined( WIN32 ) || defined( UNDER_CE )
1204 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
1206 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
1208 msg_Warn( p_this, "couldn't set a faster priority" );
1217 /*****************************************************************************
1218 * vlc_thread_join: wait until a thread exits, inner version
1219 *****************************************************************************/
1220 void __vlc_thread_join( vlc_object_t *p_this )
1222 vlc_object_internals_t *p_priv = vlc_internals( p_this );
1224 #if defined( LIBVLC_USE_PTHREAD )
1225 vlc_join (p_priv->thread_id, NULL);
1227 #elif defined( UNDER_CE ) || defined( WIN32 )
1229 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
1230 int64_t real_time, kernel_time, user_time;
1233 if( ! DuplicateHandle(GetCurrentProcess(),
1234 p_priv->thread_id->handle,
1235 GetCurrentProcess(),
1239 DUPLICATE_SAME_ACCESS) )
1241 p_priv->b_thread = false;
1242 return; /* We have a problem! */
1245 hThread = p_priv->thread_id->handle;
1248 vlc_join( p_priv->thread_id, NULL );
1250 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
1253 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
1254 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
1258 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
1259 kernel_ft.dwLowDateTime) / 10;
1262 ((((int64_t)user_ft.dwHighDateTime)<<32)|
1263 user_ft.dwLowDateTime) / 10;
1265 msg_Dbg( p_this, "thread times: "
1266 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
1267 real_time/60/1000000,
1268 (double)((real_time%(60*1000000))/1000000.0),
1269 kernel_time/60/1000000,
1270 (double)((kernel_time%(60*1000000))/1000000.0),
1271 user_time/60/1000000,
1272 (double)((user_time%(60*1000000))/1000000.0) );
1274 CloseHandle( hThread );
1277 vlc_join( p_priv->thread_id, NULL );
1281 p_priv->b_thread = false;
1284 void vlc_thread_cancel (vlc_object_t *obj)
1286 vlc_object_internals_t *priv = vlc_internals (obj);
1289 vlc_cancel (priv->thread_id);
1292 void vlc_control_cancel (int cmd, ...)
1294 /* NOTE: This function only modifies thread-specific data, so there is no
1295 * need to lock anything. */
1296 #ifdef LIBVLC_USE_PTHREAD_CANCEL
1302 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
1306 /* Main thread - cannot be cancelled anyway */
1309 nfo = malloc (sizeof (*nfo));
1311 return; /* Uho! Expect problems! */
1312 *nfo = VLC_CANCEL_INIT;
1313 vlc_threadvar_set (cancel_key, nfo);
1324 case VLC_CLEANUP_PUSH:
1326 /* cleaner is a pointer to the caller stack, no need to allocate
1327 * and copy anything. As a nice side effect, this cannot fail. */
1328 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
1329 cleaner->next = nfo->cleaners;
1330 nfo->cleaners = cleaner;
1334 case VLC_CLEANUP_POP:
1336 nfo->cleaners = nfo->cleaners->next;