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 * Print a backtrace to the standard error for debugging purpose.
58 void vlc_trace (const char *fn, const char *file, unsigned line)
60 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
61 fflush (stderr); /* needed before switch to low-level I/O */
64 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
65 backtrace_symbols_fd (stack, len, 2);
72 static inline unsigned long vlc_threadid (void)
74 #if defined (LIBVLC_USE_PTHREAD)
75 # if defined (__linux__)
76 return syscall (SYS_gettid);
79 union { pthread_t th; unsigned long int i; } v = { };
80 v.th = pthread_self ();
85 return GetCurrentThreadId ();
93 /*****************************************************************************
94 * vlc_thread_fatal: Report an error from the threading layer
95 *****************************************************************************
96 * This is mostly meant for debugging.
97 *****************************************************************************/
99 vlc_thread_fatal (const char *action, int error,
100 const char *function, const char *file, unsigned line)
102 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
103 action, error, vlc_threadid ());
104 vlc_trace (function, file, line);
106 /* Sometimes strerror_r() crashes too, so make sure we print an error
107 * message before we invoke it */
109 /* Avoid the strerror_r() prototype brain damage in glibc */
111 fprintf (stderr, " Error message: %m\n");
112 #elif !defined (WIN32)
116 switch (strerror_r (error, buf, sizeof (buf)))
121 case ERANGE: /* should never happen */
122 msg = "unknwon (too big to display)";
125 msg = "unknown (invalid error number)";
128 fprintf (stderr, " Error message: %s\n", msg);
136 # define VLC_THREAD_ASSERT( action ) \
137 if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
139 # define VLC_THREAD_ASSERT( action ) ((void)val)
143 * Per-thread cancellation data
145 #ifndef LIBVLC_USE_PTHREAD_CANCEL
146 typedef struct vlc_cancel_t
148 vlc_cleanup_t *cleaners;
157 # define VLC_CANCEL_INIT { NULL, true, false }
159 # define VLC_CANCEL_INIT { NULL, true, false, NULL }
164 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy);
166 static DWORD vlc_cancelable_wait (DWORD count, const HANDLE *handles,
169 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
172 /* Main thread - cannot be cancelled anyway */
173 return WaitForMultipleObjects (count, handles, FALSE, delay);
175 HANDLE new_handles[count + 1];
176 memcpy(new_handles, handles, count * sizeof(HANDLE));
177 new_handles[count] = nfo->cancel_event;
178 DWORD result = WaitForMultipleObjects (count + 1, new_handles, FALSE,
180 if (result == WAIT_OBJECT_0 + count)
182 vlc_cancel_self (NULL);
183 return WAIT_IO_COMPLETION;
191 DWORD SleepEx (DWORD dwMilliseconds, BOOL bAlertable)
195 DWORD result = vlc_cancelable_wait (0, NULL, dwMilliseconds);
196 return (result == WAIT_TIMEOUT) ? 0 : WAIT_IO_COMPLETION;
200 Sleep(dwMilliseconds);
205 DWORD WaitForSingleObjectEx (HANDLE hHandle, DWORD dwMilliseconds,
210 /* The MSDN documentation specifies different return codes,
211 * but in practice they are the same. We just check that it
213 #if WAIT_ABANDONED != WAIT_ABANDONED_0
214 # error Windows headers changed, code needs to be rewritten!
216 return vlc_cancelable_wait (1, &hHandle, dwMilliseconds);
220 return WaitForSingleObject (hHandle, dwMilliseconds);
224 DWORD WaitForMultipleObjectsEx (DWORD nCount, const HANDLE *lpHandles,
225 BOOL bWaitAll, DWORD dwMilliseconds,
230 /* We do not support the bWaitAll case */
232 return vlc_cancelable_wait (nCount, lpHandles, dwMilliseconds);
236 return WaitForMultipleObjects (nCount, lpHandles, bWaitAll,
243 static vlc_mutex_t super_mutex;
245 BOOL WINAPI DllMain (HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvReserved)
252 case DLL_PROCESS_ATTACH:
253 vlc_mutex_init (&super_mutex);
254 vlc_threadvar_create (&cancel_key, free);
257 case DLL_PROCESS_DETACH:
258 vlc_threadvar_delete( &cancel_key );
259 vlc_mutex_destroy (&super_mutex);
266 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
267 /* This is not prototyped under glibc, though it exists. */
268 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
271 /*****************************************************************************
272 * vlc_mutex_init: initialize a mutex
273 *****************************************************************************/
274 int vlc_mutex_init( vlc_mutex_t *p_mutex )
276 #if defined( LIBVLC_USE_PTHREAD )
277 pthread_mutexattr_t attr;
280 pthread_mutexattr_init( &attr );
283 /* Create error-checking mutex to detect problems more easily. */
284 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
285 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
287 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
290 i_result = pthread_mutex_init( p_mutex, &attr );
291 pthread_mutexattr_destroy( &attr );
294 #elif defined( WIN32 )
295 /* This creates a recursive mutex. This is OK as fast mutexes have
296 * no defined behavior in case of recursive locking. */
297 InitializeCriticalSection (&p_mutex->mutex);
298 p_mutex->initialized = 1;
304 /*****************************************************************************
305 * vlc_mutex_init: initialize a recursive mutex (Do not use)
306 *****************************************************************************/
307 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
309 #if defined( LIBVLC_USE_PTHREAD )
310 pthread_mutexattr_t attr;
313 pthread_mutexattr_init( &attr );
314 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
315 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
317 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
319 i_result = pthread_mutex_init( p_mutex, &attr );
320 pthread_mutexattr_destroy( &attr );
323 #elif defined( WIN32 )
324 InitializeCriticalSection( &p_mutex->mutex );
325 p_mutex->initialized = 1;
333 * Destroys a mutex. The mutex must not be locked.
335 * @param p_mutex mutex to destroy
336 * @return always succeeds
338 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
340 #if defined( LIBVLC_USE_PTHREAD )
341 int val = pthread_mutex_destroy( p_mutex );
342 VLC_THREAD_ASSERT ("destroying mutex");
344 #elif defined( WIN32 )
345 assert (InterlockedExchange (&p_mutex->initialized, -1) == 1);
346 DeleteCriticalSection (&p_mutex->mutex);
352 * Acquires a mutex. If needed, waits for any other thread to release it.
353 * Beware of deadlocks when locking multiple mutexes at the same time,
354 * or when using mutexes from callbacks.
356 * @param p_mutex mutex initialized with vlc_mutex_init() or
357 * vlc_mutex_init_recursive()
359 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
361 #if defined(LIBVLC_USE_PTHREAD)
362 int val = pthread_mutex_lock( p_mutex );
363 VLC_THREAD_ASSERT ("locking mutex");
365 #elif defined( WIN32 )
366 if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
367 { /* ^^ We could also lock super_mutex all the time... sluggish */
368 assert (p_mutex != &super_mutex); /* this one cannot be static */
370 vlc_mutex_lock (&super_mutex);
371 if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
372 vlc_mutex_init (p_mutex);
373 /* FIXME: destroy the mutex some time... */
374 vlc_mutex_unlock (&super_mutex);
376 assert (InterlockedExchange (&p_mutex->initialized, 1) == 1);
377 EnterCriticalSection (&p_mutex->mutex);
384 * Releases a mutex (or crashes if the mutex is not locked by the caller).
385 * @param p_mutex mutex locked with vlc_mutex_lock().
387 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
389 #if defined(LIBVLC_USE_PTHREAD)
390 int val = pthread_mutex_unlock( p_mutex );
391 VLC_THREAD_ASSERT ("unlocking mutex");
393 #elif defined( WIN32 )
394 assert (InterlockedExchange (&p_mutex->initialized, 1) == 1);
395 LeaveCriticalSection (&p_mutex->mutex);
400 /*****************************************************************************
401 * vlc_cond_init: initialize a condition variable
402 *****************************************************************************/
403 int vlc_cond_init( vlc_cond_t *p_condvar )
405 #if defined( LIBVLC_USE_PTHREAD )
406 pthread_condattr_t attr;
409 ret = pthread_condattr_init (&attr);
413 # if !defined (_POSIX_CLOCK_SELECTION)
414 /* Fairly outdated POSIX support (that was defined in 2001) */
415 # define _POSIX_CLOCK_SELECTION (-1)
417 # if (_POSIX_CLOCK_SELECTION >= 0)
418 /* NOTE: This must be the same clock as the one in mtime.c */
419 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
422 ret = pthread_cond_init (p_condvar, &attr);
423 pthread_condattr_destroy (&attr);
426 #elif defined( WIN32 )
427 /* Create a manual-reset event (manual reset is needed for broadcast). */
428 *p_condvar = CreateEvent( NULL, TRUE, FALSE, NULL );
429 return *p_condvar ? 0 : ENOMEM;
435 * Destroys a condition variable. No threads shall be waiting or signaling the
437 * @param p_condvar condition variable to destroy
439 void vlc_cond_destroy (vlc_cond_t *p_condvar)
441 #if defined( LIBVLC_USE_PTHREAD )
442 int val = pthread_cond_destroy( p_condvar );
443 VLC_THREAD_ASSERT ("destroying condition");
445 #elif defined( WIN32 )
446 CloseHandle( *p_condvar );
452 * Wakes up one thread waiting on a condition variable, if any.
453 * @param p_condvar condition variable
455 void vlc_cond_signal (vlc_cond_t *p_condvar)
457 #if defined(LIBVLC_USE_PTHREAD)
458 int val = pthread_cond_signal( p_condvar );
459 VLC_THREAD_ASSERT ("signaling condition variable");
461 #elif defined( WIN32 )
462 /* NOTE: This will cause a broadcast, that is wrong.
463 * This will also wake up the next waiting thread if no thread are yet
464 * waiting, which is also wrong. However both of these issues are allowed
465 * by the provision for spurious wakeups. Better have too many wakeups
466 * than too few (= deadlocks). */
467 SetEvent (*p_condvar);
473 * Wakes up all threads (if any) waiting on a condition variable.
474 * @param p_cond condition variable
476 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
478 #if defined (LIBVLC_USE_PTHREAD)
479 pthread_cond_broadcast (p_condvar);
481 #elif defined (WIN32)
482 SetEvent (*p_condvar);
488 * Waits for a condition variable. The calling thread will be suspended until
489 * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
490 * condition variable, the thread is cancelled with vlc_cancel(), or the
491 * system causes a "spurious" unsolicited wake-up.
493 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
494 * a recursive mutex. Although it is possible to use the same mutex for
495 * multiple condition, it is not valid to use different mutexes for the same
496 * condition variable at the same time from different threads.
498 * In case of thread cancellation, the mutex is always locked before
499 * cancellation proceeds.
501 * The canonical way to use a condition variable to wait for event foobar is:
503 vlc_mutex_lock (&lock);
504 mutex_cleanup_push (&lock); // release the mutex in case of cancellation
507 vlc_cond_wait (&wait, &lock);
509 --- foobar is now true, do something about it here --
511 vlc_cleanup_run (); // release the mutex
514 * @param p_condvar condition variable to wait on
515 * @param p_mutex mutex which is unlocked while waiting,
516 * then locked again when waking up.
517 * @param deadline <b>absolute</b> timeout
519 * @return 0 if the condition was signaled, an error code in case of timeout.
521 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
523 #if defined(LIBVLC_USE_PTHREAD)
524 int val = pthread_cond_wait( p_condvar, p_mutex );
525 VLC_THREAD_ASSERT ("waiting on condition");
527 #elif defined( WIN32 )
533 LeaveCriticalSection (&p_mutex->mutex);
534 result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
535 EnterCriticalSection (&p_mutex->mutex);
537 while (result == WAIT_IO_COMPLETION);
539 ResetEvent (*p_condvar);
545 * Waits for a condition variable up to a certain date.
546 * This works like vlc_cond_wait(), except for the additional timeout.
548 * @param p_condvar condition variable to wait on
549 * @param p_mutex mutex which is unlocked while waiting,
550 * then locked again when waking up.
551 * @param deadline <b>absolute</b> timeout
553 * @return 0 if the condition was signaled, an error code in case of timeout.
555 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
558 #if defined(LIBVLC_USE_PTHREAD)
559 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
560 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
562 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
563 if (val != ETIMEDOUT)
564 VLC_THREAD_ASSERT ("timed-waiting on condition");
567 #elif defined( WIN32 )
574 mtime_t total = (deadline - mdate ())/1000;
578 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
579 LeaveCriticalSection (&p_mutex->mutex);
580 result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
581 EnterCriticalSection (&p_mutex->mutex);
583 while (result == WAIT_IO_COMPLETION);
585 ResetEvent (*p_condvar);
587 return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
592 /*****************************************************************************
593 * vlc_tls_create: create a thread-local variable
594 *****************************************************************************/
595 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
599 #if defined( LIBVLC_USE_PTHREAD )
600 i_ret = pthread_key_create( p_tls, destr );
601 #elif defined( WIN32 )
602 /* FIXME: remember/use the destr() callback and stop leaking whatever */
604 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
606 # error Unimplemented!
611 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
613 #if defined( LIBVLC_USE_PTHREAD )
614 pthread_key_delete (*p_tls);
615 #elif defined( WIN32 )
618 # error Unimplemented!
622 #if defined (LIBVLC_USE_PTHREAD)
623 #elif defined (WIN32)
624 static unsigned __stdcall vlc_entry (void *data)
626 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
627 vlc_thread_t self = data;
629 cancel_data.cancel_event = self->cancel_event;
632 vlc_threadvar_set (&cancel_key, &cancel_data);
633 self->data = self->entry (self->data);
639 * Creates and starts new thread.
641 * @param p_handle [OUT] pointer to write the handle of the created thread to
642 * @param entry entry point for the thread
643 * @param data data parameter given to the entry point
644 * @param priority thread priority value
645 * @return 0 on success, a standard error code on error.
647 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
652 #if defined( LIBVLC_USE_PTHREAD )
654 pthread_attr_init (&attr);
656 /* Block the signals that signals interface plugin handles.
657 * If the LibVLC caller wants to handle some signals by itself, it should
658 * block these before whenever invoking LibVLC. And it must obviously not
659 * start the VLC signals interface plugin.
661 * LibVLC will normally ignore any interruption caused by an asynchronous
662 * signal during a system call. But there may well be some buggy cases
663 * where it fails to handle EINTR (bug reports welcome). Some underlying
664 * libraries might also not handle EINTR properly.
670 sigdelset (&set, SIGHUP);
671 sigaddset (&set, SIGINT);
672 sigaddset (&set, SIGQUIT);
673 sigaddset (&set, SIGTERM);
675 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
676 pthread_sigmask (SIG_BLOCK, &set, &oldset);
679 struct sched_param sp = { .sched_priority = priority, };
682 if (sp.sched_priority <= 0)
683 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
685 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
687 pthread_attr_setschedpolicy (&attr, policy);
688 pthread_attr_setschedparam (&attr, &sp);
691 /* The thread stack size.
692 * The lower the value, the less address space per thread, the highest
693 * maximum simultaneous threads per process. Too low values will cause
694 * stack overflows and weird crashes. Set with caution. Also keep in mind
695 * that 64-bits platforms consume more stack than 32-bits one.
697 * Thanks to on-demand paging, thread stack size only affects address space
698 * consumption. In terms of memory, threads only use what they need
699 * (rounded up to the page boundary).
701 * For example, on Linux i386, the default is 2 mega-bytes, which supports
702 * about 320 threads per processes. */
703 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
706 ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
707 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
710 ret = pthread_create (p_handle, &attr, entry, data);
711 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
712 pthread_attr_destroy (&attr);
714 #elif defined( WIN32 ) || defined( UNDER_CE )
715 /* When using the MSVCRT C library you have to use the _beginthreadex
716 * function instead of CreateThread, otherwise you'll end up with
717 * memory leaks and the signal functions not working (see Microsoft
718 * Knowledge Base, article 104641) */
720 vlc_thread_t th = malloc (sizeof (*th));
727 #if defined( UNDER_CE )
728 th->cancel_event = CreateEvent (NULL, FALSE, FALSE, NULL);
729 if (th->cancel_event == NULL)
734 hThread = CreateThread (NULL, 128*1024, vlc_entry, th, CREATE_SUSPENDED, NULL);
736 hThread = (HANDLE)(uintptr_t)
737 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
743 /* Thread closes the handle when exiting, duplicate it here
744 * to be on the safe side when joining. */
745 if (!DuplicateHandle (GetCurrentProcess (), hThread,
746 GetCurrentProcess (), &th->handle, 0, FALSE,
747 DUPLICATE_SAME_ACCESS))
749 CloseHandle (hThread);
754 th->handle = hThread;
757 ResumeThread (hThread);
759 SetThreadPriority (hThread, priority);
775 /* APC procedure for thread cancellation */
776 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
779 vlc_control_cancel (VLC_DO_CANCEL);
784 * Marks a thread as cancelled. Next time the target thread reaches a
785 * cancellation point (while not having disabled cancellation), it will
786 * run its cancellation cleanup handler, the thread variable destructors, and
787 * terminate. vlc_join() must be used afterward regardless of a thread being
790 void vlc_cancel (vlc_thread_t thread_id)
792 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
793 pthread_cancel (thread_id);
794 #elif defined (UNDER_CE)
795 SetEvent (thread_id->cancel_event);
796 #elif defined (WIN32)
797 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
799 # warning vlc_cancel is not implemented!
804 * Waits for a thread to complete (if needed), and destroys it.
805 * This is a cancellation point; in case of cancellation, the join does _not_
808 * @param handle thread handle
809 * @param p_result [OUT] pointer to write the thread return value or NULL
810 * @return 0 on success, a standard error code otherwise.
812 void vlc_join (vlc_thread_t handle, void **result)
814 #if defined( LIBVLC_USE_PTHREAD )
815 int val = pthread_join (handle, result);
816 VLC_THREAD_ASSERT ("joining thread");
818 #elif defined( UNDER_CE ) || defined( WIN32 )
821 while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
822 == WAIT_IO_COMPLETION);
824 CloseHandle (handle->handle);
826 *result = handle->data;
827 #if defined( UNDER_CE )
828 CloseHandle (handle->cancel_event);
836 * Save the current cancellation state (enabled or disabled), then disable
837 * cancellation for the calling thread.
838 * This function must be called before entering a piece of code that is not
839 * cancellation-safe, unless it can be proven that the calling thread will not
841 * @return Previous cancellation state (opaque value for vlc_restorecancel()).
843 int vlc_savecancel (void)
847 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
848 int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
849 VLC_THREAD_ASSERT ("saving cancellation");
852 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
854 return false; /* Main thread - cannot be cancelled anyway */
856 state = nfo->killable;
857 nfo->killable = false;
864 * Restore the cancellation state for the calling thread.
865 * @param state previous state as returned by vlc_savecancel().
866 * @return Nothing, always succeeds.
868 void vlc_restorecancel (int state)
870 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
874 val = pthread_setcancelstate (state, &oldstate);
875 /* This should fail if an invalid value for given for state */
876 VLC_THREAD_ASSERT ("restoring cancellation");
878 if (oldstate != PTHREAD_CANCEL_DISABLE)
879 vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
880 __func__, __FILE__, __LINE__);
882 pthread_setcancelstate (state, NULL);
886 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
887 assert (state == false || state == true);
890 return; /* Main thread - cannot be cancelled anyway */
892 assert (!nfo->killable);
893 nfo->killable = state != 0;
899 * Issues an explicit deferred cancellation point.
900 * This has no effect if thread cancellation is disabled.
901 * This can be called when there is a rather slow non-sleeping operation.
902 * This is also used to force a cancellation point in a function that would
903 * otherwise "not always" be a one (block_FifoGet() is an example).
905 void vlc_testcancel (void)
907 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
908 pthread_testcancel ();
911 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
913 return; /* Main thread - cannot be cancelled anyway */
915 if (nfo->killable && nfo->killed)
917 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
919 # if defined (LIBVLC_USE_PTHREAD)
920 pthread_exit (PTHREAD_CANCELLED);
921 # elif defined (UNDER_CE)
923 # elif defined (WIN32)
926 # error Not implemented!
933 struct vlc_thread_boot
935 void * (*entry) (vlc_object_t *);
936 vlc_object_t *object;
939 static void *thread_entry (void *data)
941 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
942 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
945 msg_Dbg (obj, "thread started");
947 msg_Dbg (obj, "thread ended");
952 #undef vlc_thread_create
953 /*****************************************************************************
954 * vlc_thread_create: create a thread
955 *****************************************************************************
956 * Note that i_priority is only taken into account on platforms supporting
957 * userland real-time priority threads.
958 *****************************************************************************/
959 int vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
960 const char *psz_name, void *(*func) ( vlc_object_t * ),
964 vlc_object_internals_t *p_priv = vlc_internals( p_this );
966 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
970 boot->object = p_this;
972 /* Make sure we don't re-create a thread if the object has already one */
973 assert( !p_priv->b_thread );
975 #if defined( LIBVLC_USE_PTHREAD )
977 if( config_GetInt( p_this, "rt-priority" ) > 0 )
980 /* Hack to avoid error msg */
981 if( config_GetType( p_this, "rt-offset" ) )
982 i_priority += config_GetInt( p_this, "rt-offset" );
986 p_priv->b_thread = true;
987 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
989 msg_Dbg( p_this, "thread (%s) created at priority %d (%s:%d)",
990 psz_name, i_priority, psz_file, i_line );
993 p_priv->b_thread = false;
995 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
996 psz_name, psz_file, i_line );
1002 /*****************************************************************************
1003 * vlc_thread_set_priority: set the priority of the current thread when we
1004 * couldn't set it in vlc_thread_create (for instance for the main thread)
1005 *****************************************************************************/
1006 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
1007 int i_line, int i_priority )
1009 vlc_object_internals_t *p_priv = vlc_internals( p_this );
1011 if( !p_priv->b_thread )
1013 msg_Err( p_this, "couldn't set priority of non-existent thread" );
1017 #if defined( LIBVLC_USE_PTHREAD )
1019 if( config_GetInt( p_this, "rt-priority" ) > 0 )
1022 int i_error, i_policy;
1023 struct sched_param param;
1025 memset( ¶m, 0, sizeof(struct sched_param) );
1026 if( config_GetType( p_this, "rt-offset" ) )
1027 i_priority += config_GetInt( p_this, "rt-offset" );
1028 if( i_priority <= 0 )
1030 param.sched_priority = (-1) * i_priority;
1031 i_policy = SCHED_OTHER;
1035 param.sched_priority = i_priority;
1036 i_policy = SCHED_RR;
1038 if( (i_error = pthread_setschedparam( p_priv->thread_id,
1039 i_policy, ¶m )) )
1042 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
1048 #elif defined( WIN32 ) || defined( UNDER_CE )
1049 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
1051 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
1053 msg_Warn( p_this, "couldn't set a faster priority" );
1062 /*****************************************************************************
1063 * vlc_thread_join: wait until a thread exits, inner version
1064 *****************************************************************************/
1065 void __vlc_thread_join( vlc_object_t *p_this )
1067 vlc_object_internals_t *p_priv = vlc_internals( p_this );
1069 #if defined( LIBVLC_USE_PTHREAD )
1070 vlc_join (p_priv->thread_id, NULL);
1072 #elif defined( UNDER_CE ) || defined( WIN32 )
1074 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
1075 int64_t real_time, kernel_time, user_time;
1078 if( ! DuplicateHandle(GetCurrentProcess(),
1079 p_priv->thread_id->handle,
1080 GetCurrentProcess(),
1084 DUPLICATE_SAME_ACCESS) )
1086 p_priv->b_thread = false;
1087 return; /* We have a problem! */
1090 hThread = p_priv->thread_id->handle;
1093 vlc_join( p_priv->thread_id, NULL );
1095 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
1098 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
1099 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
1103 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
1104 kernel_ft.dwLowDateTime) / 10;
1107 ((((int64_t)user_ft.dwHighDateTime)<<32)|
1108 user_ft.dwLowDateTime) / 10;
1110 msg_Dbg( p_this, "thread times: "
1111 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
1112 real_time/60/1000000,
1113 (double)((real_time%(60*1000000))/1000000.0),
1114 kernel_time/60/1000000,
1115 (double)((kernel_time%(60*1000000))/1000000.0),
1116 user_time/60/1000000,
1117 (double)((user_time%(60*1000000))/1000000.0) );
1119 CloseHandle( hThread );
1122 vlc_join( p_priv->thread_id, NULL );
1126 p_priv->b_thread = false;
1129 void vlc_thread_cancel (vlc_object_t *obj)
1131 vlc_object_internals_t *priv = vlc_internals (obj);
1134 vlc_cancel (priv->thread_id);
1137 void vlc_control_cancel (int cmd, ...)
1139 /* NOTE: This function only modifies thread-specific data, so there is no
1140 * need to lock anything. */
1141 #ifdef LIBVLC_USE_PTHREAD_CANCEL
1147 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
1151 /* Main thread - cannot be cancelled anyway */
1154 nfo = malloc (sizeof (*nfo));
1156 return; /* Uho! Expect problems! */
1157 *nfo = VLC_CANCEL_INIT;
1158 vlc_threadvar_set (&cancel_key, nfo);
1169 case VLC_CLEANUP_PUSH:
1171 /* cleaner is a pointer to the caller stack, no need to allocate
1172 * and copy anything. As a nice side effect, this cannot fail. */
1173 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
1174 cleaner->next = nfo->cleaners;
1175 nfo->cleaners = cleaner;
1179 case VLC_CLEANUP_POP:
1181 nfo->cleaners = nfo->cleaners->next;