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 static vlc_threadvar_t cancel_key;
48 #ifdef HAVE_EXECINFO_H
49 # include <execinfo.h>
53 * Print a backtrace to the standard error for debugging purpose.
55 void vlc_trace (const char *fn, const char *file, unsigned line)
57 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
58 fflush (stderr); /* needed before switch to low-level I/O */
61 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
62 backtrace_symbols_fd (stack, len, 2);
69 static inline unsigned long vlc_threadid (void)
71 #if defined(LIBVLC_USE_PTHREAD)
72 union { pthread_t th; unsigned long int i; } v = { };
73 v.th = pthread_self ();
77 return GetCurrentThreadId ();
85 /*****************************************************************************
86 * vlc_thread_fatal: Report an error from the threading layer
87 *****************************************************************************
88 * This is mostly meant for debugging.
89 *****************************************************************************/
91 vlc_thread_fatal (const char *action, int error,
92 const char *function, const char *file, unsigned line)
94 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
95 action, error, vlc_threadid ());
96 vlc_trace (function, file, line);
98 /* Sometimes strerror_r() crashes too, so make sure we print an error
99 * message before we invoke it */
101 /* Avoid the strerror_r() prototype brain damage in glibc */
103 fprintf (stderr, " Error message: %m\n");
104 #elif !defined (WIN32)
108 switch (strerror_r (error, buf, sizeof (buf)))
113 case ERANGE: /* should never happen */
114 msg = "unknwon (too big to display)";
117 msg = "unknown (invalid error number)";
120 fprintf (stderr, " Error message: %s\n", msg);
128 # define VLC_THREAD_ASSERT( action ) \
129 if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
131 # define VLC_THREAD_ASSERT( action ) ((void)val)
135 * Per-thread cancellation data
137 #ifndef LIBVLC_USE_PTHREAD_CANCEL
138 typedef struct vlc_cancel_t
140 vlc_cleanup_t *cleaners;
145 # define VLC_CANCEL_INIT { NULL, true, false }
149 static vlc_mutex_t super_mutex;
151 BOOL WINAPI DllMain (HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvReserved)
158 case DLL_PROCESS_ATTACH:
159 vlc_mutex_init (&super_mutex);
160 vlc_threadvar_create (&cancel_key, free);
163 case DLL_PROCESS_DETACH:
164 vlc_threadvar_delete( &cancel_key );
165 vlc_mutex_destroy (&super_mutex);
172 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
173 /* This is not prototyped under glibc, though it exists. */
174 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
177 /*****************************************************************************
178 * vlc_mutex_init: initialize a mutex
179 *****************************************************************************/
180 int vlc_mutex_init( vlc_mutex_t *p_mutex )
182 #if defined( LIBVLC_USE_PTHREAD )
183 pthread_mutexattr_t attr;
186 pthread_mutexattr_init( &attr );
189 /* Create error-checking mutex to detect problems more easily. */
190 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
191 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
193 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
196 i_result = pthread_mutex_init( p_mutex, &attr );
197 pthread_mutexattr_destroy( &attr );
200 #elif defined( WIN32 )
201 /* This creates a recursive mutex. This is OK as fast mutexes have
202 * no defined behavior in case of recursive locking. */
203 InitializeCriticalSection (&p_mutex->mutex);
209 /*****************************************************************************
210 * vlc_mutex_init: initialize a recursive mutex (Do not use)
211 *****************************************************************************/
212 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
214 #if defined( LIBVLC_USE_PTHREAD )
215 pthread_mutexattr_t attr;
218 pthread_mutexattr_init( &attr );
219 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
220 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
222 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
224 i_result = pthread_mutex_init( p_mutex, &attr );
225 pthread_mutexattr_destroy( &attr );
228 #elif defined( WIN32 )
229 InitializeCriticalSection( &p_mutex->mutex );
230 InterlockedIncrement (&p_mutex->initialized);
239 * Destroys a mutex. The mutex must not be locked.
241 * @param p_mutex mutex to destroy
242 * @return always succeeds
244 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
246 #if defined( LIBVLC_USE_PTHREAD )
247 int val = pthread_mutex_destroy( p_mutex );
248 VLC_THREAD_ASSERT ("destroying mutex");
250 #elif defined( WIN32 )
251 InterlockedDecrement (&p_mutex->initialized);
252 DeleteCriticalSection (&p_mutex->mutex);
258 * Acquires a mutex. If needed, waits for any other thread to release it.
259 * Beware of deadlocks when locking multiple mutexes at the same time,
260 * or when using mutexes from callbacks.
262 * @param p_mutex mutex initialized with vlc_mutex_init() or
263 * vlc_mutex_init_recursive()
265 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
267 #if defined(LIBVLC_USE_PTHREAD)
268 int val = pthread_mutex_lock( p_mutex );
269 VLC_THREAD_ASSERT ("locking mutex");
271 #elif defined( WIN32 )
272 if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
273 { /* ^^ We could also lock super_mutex all the time... sluggish */
274 assert (p_mutex != &super_mutex); /* this one cannot be static */
276 vlc_mutex_lock (&super_mutex);
277 vlc_mutex_init (p_mutex);
278 /* FIXME: destroy the mutex some time... */
279 vlc_mutex_unlock (&super_mutex);
281 EnterCriticalSection (&p_mutex->mutex);
288 * Releases a mutex (or crashes if the mutex is not locked by the caller).
289 * @param p_mutex mutex locked with vlc_mutex_lock().
291 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
293 #if defined(LIBVLC_USE_PTHREAD)
294 int val = pthread_mutex_unlock( p_mutex );
295 VLC_THREAD_ASSERT ("unlocking mutex");
297 #elif defined( WIN32 )
298 LeaveCriticalSection (&p_mutex->mutex);
303 /*****************************************************************************
304 * vlc_cond_init: initialize a condition variable
305 *****************************************************************************/
306 int vlc_cond_init( vlc_cond_t *p_condvar )
308 #if defined( LIBVLC_USE_PTHREAD )
309 pthread_condattr_t attr;
312 ret = pthread_condattr_init (&attr);
316 # if !defined (_POSIX_CLOCK_SELECTION)
317 /* Fairly outdated POSIX support (that was defined in 2001) */
318 # define _POSIX_CLOCK_SELECTION (-1)
320 # if (_POSIX_CLOCK_SELECTION >= 0)
321 /* NOTE: This must be the same clock as the one in mtime.c */
322 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
325 ret = pthread_cond_init (p_condvar, &attr);
326 pthread_condattr_destroy (&attr);
329 #elif defined( WIN32 )
330 /* Create a manual-reset event (manual reset is needed for broadcast). */
331 *p_condvar = CreateEvent( NULL, TRUE, FALSE, NULL );
332 return *p_condvar ? 0 : ENOMEM;
338 * Destroys a condition variable. No threads shall be waiting or signaling the
340 * @param p_condvar condition variable to destroy
342 void vlc_cond_destroy (vlc_cond_t *p_condvar)
344 #if defined( LIBVLC_USE_PTHREAD )
345 int val = pthread_cond_destroy( p_condvar );
346 VLC_THREAD_ASSERT ("destroying condition");
348 #elif defined( WIN32 )
349 CloseHandle( *p_condvar );
355 * Wakes up one thread waiting on a condition variable, if any.
356 * @param p_condvar condition variable
358 void vlc_cond_signal (vlc_cond_t *p_condvar)
360 #if defined(LIBVLC_USE_PTHREAD)
361 int val = pthread_cond_signal( p_condvar );
362 VLC_THREAD_ASSERT ("signaling condition variable");
364 #elif defined( WIN32 )
365 /* NOTE: This will cause a broadcast, that is wrong.
366 * This will also wake up the next waiting thread if no thread are yet
367 * waiting, which is also wrong. However both of these issues are allowed
368 * by the provision for spurious wakeups. Better have too many wakeups
369 * than too few (= deadlocks). */
370 SetEvent (*p_condvar);
376 * Wakes up all threads (if any) waiting on a condition variable.
377 * @param p_cond condition variable
379 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
381 #if defined (LIBVLC_USE_PTHREAD)
382 pthread_cond_broadcast (p_condvar);
384 #elif defined (WIN32)
385 SetEvent (*p_condvar);
392 # define WaitForMultipleObjectsEx(a,b,c) WaitForMultipleObjects(a,b)
396 * Waits for a condition variable. The calling thread will be suspended until
397 * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
398 * condition variable, the thread is cancelled with vlc_cancel(), or the
399 * system causes a "spurious" unsolicited wake-up.
401 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
402 * a recursive mutex. Although it is possible to use the same mutex for
403 * multiple condition, it is not valid to use different mutexes for the same
404 * condition variable at the same time from different threads.
406 * In case of thread cancellation, the mutex is always locked before
407 * cancellation proceeds.
409 * The canonical way to use a condition variable to wait for event foobar is:
411 vlc_mutex_lock (&lock);
412 mutex_cleanup_push (&lock); // release the mutex in case of cancellation
415 vlc_cond_wait (&wait, &lock);
417 --- foobar is now true, do something about it here --
419 vlc_cleanup_run (); // release the mutex
422 * @param p_condvar condition variable to wait on
423 * @param p_mutex mutex which is unlocked while waiting,
424 * then locked again when waking up.
425 * @param deadline <b>absolute</b> timeout
427 * @return 0 if the condition was signaled, an error code in case of timeout.
429 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
431 #if defined(LIBVLC_USE_PTHREAD)
432 int val = pthread_cond_wait( p_condvar, p_mutex );
433 VLC_THREAD_ASSERT ("waiting on condition");
435 #elif defined( WIN32 )
441 LeaveCriticalSection (&p_mutex->mutex);
442 result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
443 EnterCriticalSection (&p_mutex->mutex);
445 while (result == WAIT_IO_COMPLETION);
447 ResetEvent (*p_condvar);
453 * Waits for a condition variable up to a certain date.
454 * This works like vlc_cond_wait(), except for the additional timeout.
456 * @param p_condvar condition variable to wait on
457 * @param p_mutex mutex which is unlocked while waiting,
458 * then locked again when waking up.
459 * @param deadline <b>absolute</b> timeout
461 * @return 0 if the condition was signaled, an error code in case of timeout.
463 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
466 #if defined(LIBVLC_USE_PTHREAD)
467 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
468 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
470 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
471 if (val != ETIMEDOUT)
472 VLC_THREAD_ASSERT ("timed-waiting on condition");
475 #elif defined( WIN32 )
482 mtime_t total = (deadline - mdate ())/1000;
486 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
487 LeaveCriticalSection (&p_mutex->mutex);
488 result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
489 EnterCriticalSection (&p_mutex->mutex);
491 while (result == WAIT_IO_COMPLETION);
493 ResetEvent (*p_condvar);
495 return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
500 /*****************************************************************************
501 * vlc_tls_create: create a thread-local variable
502 *****************************************************************************/
503 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
507 #if defined( LIBVLC_USE_PTHREAD )
508 i_ret = pthread_key_create( p_tls, destr );
509 #elif defined( UNDER_CE )
511 #elif defined( WIN32 )
512 /* FIXME: remember/use the destr() callback and stop leaking whatever */
514 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
516 # error Unimplemented!
521 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
523 #if defined( LIBVLC_USE_PTHREAD )
524 pthread_key_delete (*p_tls);
525 #elif defined( UNDER_CE )
526 #elif defined( WIN32 )
529 # error Unimplemented!
533 #if defined (LIBVLC_USE_PTHREAD)
534 #elif defined (WIN32)
535 static unsigned __stdcall vlc_entry (void *data)
537 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
538 vlc_thread_t self = data;
540 vlc_threadvar_set (&cancel_key, &cancel_data);
541 self->data = self->entry (self->data);
547 * Creates and starts new thread.
549 * @param p_handle [OUT] pointer to write the handle of the created thread to
550 * @param entry entry point for the thread
551 * @param data data parameter given to the entry point
552 * @param priority thread priority value
553 * @return 0 on success, a standard error code on error.
555 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
560 #if defined( LIBVLC_USE_PTHREAD )
562 pthread_attr_init (&attr);
564 /* Block the signals that signals interface plugin handles.
565 * If the LibVLC caller wants to handle some signals by itself, it should
566 * block these before whenever invoking LibVLC. And it must obviously not
567 * start the VLC signals interface plugin.
569 * LibVLC will normally ignore any interruption caused by an asynchronous
570 * signal during a system call. But there may well be some buggy cases
571 * where it fails to handle EINTR (bug reports welcome). Some underlying
572 * libraries might also not handle EINTR properly.
578 sigdelset (&set, SIGHUP);
579 sigaddset (&set, SIGINT);
580 sigaddset (&set, SIGQUIT);
581 sigaddset (&set, SIGTERM);
583 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
584 pthread_sigmask (SIG_BLOCK, &set, &oldset);
587 struct sched_param sp = { .sched_priority = priority, };
590 if (sp.sched_priority <= 0)
591 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
593 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
595 pthread_attr_setschedpolicy (&attr, policy);
596 pthread_attr_setschedparam (&attr, &sp);
599 /* The thread stack size.
600 * The lower the value, the less address space per thread, the highest
601 * maximum simultaneous threads per process. Too low values will cause
602 * stack overflows and weird crashes. Set with caution. Also keep in mind
603 * that 64-bits platforms consume more stack than 32-bits one.
605 * Thanks to on-demand paging, thread stack size only affects address space
606 * consumption. In terms of memory, threads only use what they need
607 * (rounded up to the page boundary).
609 * For example, on Linux i386, the default is 2 mega-bytes, which supports
610 * about 320 threads per processes. */
611 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
614 ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
615 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
618 ret = pthread_create (p_handle, &attr, entry, data);
619 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
620 pthread_attr_destroy (&attr);
622 #elif defined( WIN32 ) || defined( UNDER_CE )
623 /* When using the MSVCRT C library you have to use the _beginthreadex
624 * function instead of CreateThread, otherwise you'll end up with
625 * memory leaks and the signal functions not working (see Microsoft
626 * Knowledge Base, article 104641) */
628 vlc_thread_t th = malloc (sizeof (*th));
635 #if defined( UNDER_CE )
636 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
638 hThread = (HANDLE)(uintptr_t)
639 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
644 /* Thread closes the handle when exiting, duplicate it here
645 * to be on the safe side when joining. */
646 if (!DuplicateHandle (GetCurrentProcess (), hThread,
647 GetCurrentProcess (), &th->handle, 0, FALSE,
648 DUPLICATE_SAME_ACCESS))
650 CloseHandle (hThread);
655 ResumeThread (hThread);
657 SetThreadPriority (hThread, priority);
673 /* APC procedure for thread cancellation */
674 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
677 vlc_control_cancel (VLC_DO_CANCEL);
682 * Marks a thread as cancelled. Next time the target thread reaches a
683 * cancellation point (while not having disabled cancellation), it will
684 * run its cancellation cleanup handler, the thread variable destructors, and
685 * terminate. vlc_join() must be used afterward regardless of a thread being
688 void vlc_cancel (vlc_thread_t thread_id)
690 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
691 pthread_cancel (thread_id);
692 #elif defined (WIN32)
693 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
695 # warning vlc_cancel is not implemented!
700 * Waits for a thread to complete (if needed), and destroys it.
701 * This is a cancellation point; in case of cancellation, the join does _not_
704 * @param handle thread handle
705 * @param p_result [OUT] pointer to write the thread return value or NULL
706 * @return 0 on success, a standard error code otherwise.
708 void vlc_join (vlc_thread_t handle, void **result)
710 #if defined( LIBVLC_USE_PTHREAD )
711 int val = pthread_join (handle, result);
713 vlc_thread_fatal ("joining thread", val, __func__, __FILE__, __LINE__);
715 #elif defined( UNDER_CE ) || defined( WIN32 )
718 while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
719 == WAIT_IO_COMPLETION);
721 CloseHandle (handle->handle);
723 *result = handle->data;
730 struct vlc_thread_boot
732 void * (*entry) (vlc_object_t *);
733 vlc_object_t *object;
736 static void *thread_entry (void *data)
738 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
739 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
742 msg_Dbg (obj, "thread started");
744 msg_Dbg (obj, "thread ended");
749 /*****************************************************************************
750 * vlc_thread_create: create a thread, inner version
751 *****************************************************************************
752 * Note that i_priority is only taken into account on platforms supporting
753 * userland real-time priority threads.
754 *****************************************************************************/
755 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
756 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
757 int i_priority, bool b_wait )
760 vlc_object_internals_t *p_priv = vlc_internals( p_this );
762 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
766 boot->object = p_this;
768 /* Make sure we don't re-create a thread if the object has already one */
769 assert( !p_priv->b_thread );
771 #if defined( LIBVLC_USE_PTHREAD )
773 sem_init (&p_priv->thread_ready, 0, 0);
775 if( config_GetInt( p_this, "rt-priority" ) > 0 )
778 /* Hack to avoid error msg */
779 if( config_GetType( p_this, "rt-offset" ) )
780 i_priority += config_GetInt( p_this, "rt-offset" );
782 #elif defined (WIN32)
784 p_priv->thread_ready = CreateEvent (NULL, TRUE, FALSE, NULL);
787 p_priv->b_thread = true;
788 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
791 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
792 (unsigned long)p_priv->thread_id, psz_name, i_priority,
796 msg_Dbg( p_this, "waiting for thread initialization" );
797 #if defined (LIBVLC_USE_PTHREAD)
798 sem_wait (&p_priv->thread_ready);
799 sem_destroy (&p_priv->thread_ready);
800 #elif defined (WIN32)
801 WaitForSingleObject (p_priv->thread_ready, INFINITE);
802 CloseHandle (p_priv->thread_ready);
808 p_priv->b_thread = false;
810 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
811 psz_name, psz_file, i_line );
817 #undef vlc_thread_ready
818 void vlc_thread_ready (vlc_object_t *obj)
820 vlc_object_internals_t *priv = vlc_internals (obj);
822 assert (priv->b_thread);
823 #if defined (LIBVLC_USE_PTHREAD)
824 assert (pthread_equal (pthread_self (), priv->thread_id));
825 sem_post (&priv->thread_ready);
826 #elif defined (WIN32)
827 SetEvent (priv->thread_ready);
831 /*****************************************************************************
832 * vlc_thread_set_priority: set the priority of the current thread when we
833 * couldn't set it in vlc_thread_create (for instance for the main thread)
834 *****************************************************************************/
835 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
836 int i_line, int i_priority )
838 vlc_object_internals_t *p_priv = vlc_internals( p_this );
840 if( !p_priv->b_thread )
842 msg_Err( p_this, "couldn't set priority of non-existent thread" );
846 #if defined( LIBVLC_USE_PTHREAD )
848 if( config_GetInt( p_this, "rt-priority" ) > 0 )
851 int i_error, i_policy;
852 struct sched_param param;
854 memset( ¶m, 0, sizeof(struct sched_param) );
855 if( config_GetType( p_this, "rt-offset" ) )
856 i_priority += config_GetInt( p_this, "rt-offset" );
857 if( i_priority <= 0 )
859 param.sched_priority = (-1) * i_priority;
860 i_policy = SCHED_OTHER;
864 param.sched_priority = i_priority;
867 if( (i_error = pthread_setschedparam( p_priv->thread_id,
868 i_policy, ¶m )) )
871 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
877 #elif defined( WIN32 ) || defined( UNDER_CE )
878 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
880 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
882 msg_Warn( p_this, "couldn't set a faster priority" );
891 /*****************************************************************************
892 * vlc_thread_join: wait until a thread exits, inner version
893 *****************************************************************************/
894 void __vlc_thread_join( vlc_object_t *p_this )
896 vlc_object_internals_t *p_priv = vlc_internals( p_this );
898 #if defined( LIBVLC_USE_PTHREAD )
899 vlc_join (p_priv->thread_id, NULL);
901 #elif defined( UNDER_CE ) || defined( WIN32 )
903 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
904 int64_t real_time, kernel_time, user_time;
906 if( ! DuplicateHandle(GetCurrentProcess(),
907 p_priv->thread_id->handle,
912 DUPLICATE_SAME_ACCESS) )
914 p_priv->b_thread = false;
915 return; /* We have a problem! */
918 vlc_join( p_priv->thread_id, NULL );
920 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
923 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
924 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
928 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
929 kernel_ft.dwLowDateTime) / 10;
932 ((((int64_t)user_ft.dwHighDateTime)<<32)|
933 user_ft.dwLowDateTime) / 10;
935 msg_Dbg( p_this, "thread times: "
936 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
937 real_time/60/1000000,
938 (double)((real_time%(60*1000000))/1000000.0),
939 kernel_time/60/1000000,
940 (double)((kernel_time%(60*1000000))/1000000.0),
941 user_time/60/1000000,
942 (double)((user_time%(60*1000000))/1000000.0) );
944 CloseHandle( hThread );
947 vlc_join( p_priv->thread_id, NULL );
951 p_priv->b_thread = false;
954 void vlc_thread_cancel (vlc_object_t *obj)
956 vlc_object_internals_t *priv = vlc_internals (obj);
959 vlc_cancel (priv->thread_id);
962 void vlc_control_cancel (int cmd, ...)
964 /* NOTE: This function only modifies thread-specific data, so there is no
965 * need to lock anything. */
966 #ifdef LIBVLC_USE_PTHREAD_CANCEL
972 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
976 /* Main thread - cannot be cancelled anyway */
979 nfo = malloc (sizeof (*nfo));
981 return; /* Uho! Expect problems! */
982 *nfo = VLC_CANCEL_INIT;
983 vlc_threadvar_set (&cancel_key, nfo);
990 case VLC_SAVE_CANCEL:
992 int *p_state = va_arg (ap, int *);
993 *p_state = nfo->killable;
994 nfo->killable = false;
998 case VLC_RESTORE_CANCEL:
1000 int state = va_arg (ap, int);
1001 nfo->killable = state != 0;
1005 case VLC_TEST_CANCEL:
1006 if (nfo->killable && nfo->killed)
1008 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
1013 #if defined (LIBVLC_USE_PTHREAD)
1014 pthread_exit (PTHREAD_CANCELLED);
1015 #elif defined (UNDER_CE)
1017 #elif defined (WIN32)
1020 # error Not implemented!
1029 case VLC_CLEANUP_PUSH:
1031 /* cleaner is a pointer to the caller stack, no need to allocate
1032 * and copy anything. As a nice side effect, this cannot fail. */
1033 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
1034 cleaner->next = nfo->cleaners;
1035 nfo->cleaners = cleaner;
1039 case VLC_CLEANUP_POP:
1041 nfo->cleaners = nfo->cleaners->next;