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 /*****************************************************************************
43 * Global mutex for lazy initialization of the threads system
44 *****************************************************************************/
45 static volatile unsigned i_initializations = 0;
47 #if defined( LIBVLC_USE_PTHREAD )
50 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
52 static vlc_threadvar_t cancel_key;
57 vlc_dictionary_t list;
61 #ifdef HAVE_EXECINFO_H
62 # include <execinfo.h>
66 * Print a backtrace to the standard error for debugging purpose.
68 void vlc_trace (const char *fn, const char *file, unsigned line)
70 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
71 fflush (stderr); /* needed before switch to low-level I/O */
74 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
75 backtrace_symbols_fd (stack, len, 2);
82 static inline unsigned long vlc_threadid (void)
84 #if defined(LIBVLC_USE_PTHREAD)
85 union { pthread_t th; unsigned long int i; } v = { };
86 v.th = pthread_self ();
90 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);
141 # define VLC_THREAD_ASSERT( action ) \
142 if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
144 # define VLC_THREAD_ASSERT( action ) ((void)val)
148 * Per-thread cancellation data
150 #ifndef LIBVLC_USE_PTHREAD_CANCEL
151 typedef struct vlc_cancel_t
153 vlc_cleanup_t *cleaners;
158 # define VLC_CANCEL_INIT { NULL, true, false }
161 /*****************************************************************************
162 * vlc_threads_init: initialize threads system
163 *****************************************************************************
164 * This function requires lazy initialization of a global lock in order to
165 * keep the library really thread-safe. Some architectures don't support this
166 * and thus do not guarantee the complete reentrancy.
167 *****************************************************************************/
168 int vlc_threads_init( void )
170 /* If we have lazy mutex initialization, use it. Otherwise, we just
171 * hope nothing wrong happens. */
172 #if defined( LIBVLC_USE_PTHREAD )
173 pthread_mutex_lock( &once_mutex );
176 if( i_initializations == 0 )
178 vlc_dictionary_init (&named_mutexes.list, 0);
179 vlc_mutex_init (&named_mutexes.lock);
180 #ifndef LIBVLC_USE_PTHREAD_CANCEL
181 vlc_threadvar_create( &cancel_key, free );
186 #if defined( LIBVLC_USE_PTHREAD )
187 pthread_mutex_unlock( &once_mutex );
193 /*****************************************************************************
194 * vlc_threads_end: stop threads system
195 *****************************************************************************
196 * FIXME: This function is far from being threadsafe.
197 *****************************************************************************/
198 void vlc_threads_end( void )
200 #if defined( LIBVLC_USE_PTHREAD )
201 pthread_mutex_lock( &once_mutex );
204 assert( i_initializations > 0 );
206 if( i_initializations == 1 )
208 #ifndef LIBVLC_USE_PTHREAD
209 vlc_threadvar_delete( &cancel_key );
211 vlc_mutex_destroy (&named_mutexes.lock);
212 vlc_dictionary_clear (&named_mutexes.list);
216 #if defined( LIBVLC_USE_PTHREAD )
217 pthread_mutex_unlock( &once_mutex );
221 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
222 /* This is not prototyped under glibc, though it exists. */
223 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
226 /*****************************************************************************
227 * vlc_mutex_init: initialize a mutex
228 *****************************************************************************/
229 int vlc_mutex_init( vlc_mutex_t *p_mutex )
231 #if defined( LIBVLC_USE_PTHREAD )
232 pthread_mutexattr_t attr;
235 pthread_mutexattr_init( &attr );
238 /* Create error-checking mutex to detect problems more easily. */
239 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
240 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
242 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
245 i_result = pthread_mutex_init( p_mutex, &attr );
246 pthread_mutexattr_destroy( &attr );
249 #elif defined( WIN32 )
250 /* This creates a recursive mutex. This is OK as fast mutexes have
251 * no defined behavior in case of recursive locking. */
252 InitializeCriticalSection (&p_mutex->mutex);
258 /*****************************************************************************
259 * vlc_mutex_init: initialize a recursive mutex (Do not use)
260 *****************************************************************************/
261 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
263 #if defined( LIBVLC_USE_PTHREAD )
264 pthread_mutexattr_t attr;
267 pthread_mutexattr_init( &attr );
268 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
269 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
271 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
273 i_result = pthread_mutex_init( p_mutex, &attr );
274 pthread_mutexattr_destroy( &attr );
277 #elif defined( WIN32 )
278 InitializeCriticalSection( &p_mutex->mutex );
286 * Destroys a mutex. The mutex must not be locked.
288 * @param p_mutex mutex to destroy
289 * @return always succeeds
291 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
293 #if defined( LIBVLC_USE_PTHREAD )
294 int val = pthread_mutex_destroy( p_mutex );
295 VLC_THREAD_ASSERT ("destroying mutex");
297 #elif defined( WIN32 )
298 DeleteCriticalSection (&p_mutex->mutex);
304 * Acquires a mutex. If needed, waits for any other thread to release it.
305 * Beware of deadlocks when locking multiple mutexes at the same time,
306 * or when using mutexes from callbacks.
308 * @param p_mutex mutex initialized with vlc_mutex_init() or
309 * vlc_mutex_init_recursive()
311 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
313 #if defined(LIBVLC_USE_PTHREAD)
314 int val = pthread_mutex_lock( p_mutex );
315 VLC_THREAD_ASSERT ("locking mutex");
317 #elif defined( WIN32 )
318 EnterCriticalSection (&p_mutex->mutex);
325 * Releases a mutex (or crashes if the mutex is not locked by the caller).
326 * @param p_mutex mutex locked with vlc_mutex_lock().
328 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
330 #if defined(LIBVLC_USE_PTHREAD)
331 int val = pthread_mutex_unlock( p_mutex );
332 VLC_THREAD_ASSERT ("unlocking mutex");
334 #elif defined( WIN32 )
335 LeaveCriticalSection (&p_mutex->mutex);
340 /*****************************************************************************
341 * vlc_cond_init: initialize a condition variable
342 *****************************************************************************/
343 int vlc_cond_init( vlc_cond_t *p_condvar )
345 #if defined( LIBVLC_USE_PTHREAD )
346 pthread_condattr_t attr;
349 ret = pthread_condattr_init (&attr);
353 # if !defined (_POSIX_CLOCK_SELECTION)
354 /* Fairly outdated POSIX support (that was defined in 2001) */
355 # define _POSIX_CLOCK_SELECTION (-1)
357 # if (_POSIX_CLOCK_SELECTION >= 0)
358 /* NOTE: This must be the same clock as the one in mtime.c */
359 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
362 ret = pthread_cond_init (p_condvar, &attr);
363 pthread_condattr_destroy (&attr);
366 #elif defined( WIN32 )
367 /* Create a manual-reset event (manual reset is needed for broadcast). */
368 *p_condvar = CreateEvent( NULL, TRUE, FALSE, NULL );
369 return *p_condvar ? 0 : ENOMEM;
375 * Destroys a condition variable. No threads shall be waiting or signaling the
377 * @param p_condvar condition variable to destroy
379 void vlc_cond_destroy (vlc_cond_t *p_condvar)
381 #if defined( LIBVLC_USE_PTHREAD )
382 int val = pthread_cond_destroy( p_condvar );
383 VLC_THREAD_ASSERT ("destroying condition");
385 #elif defined( WIN32 )
386 CloseHandle( *p_condvar );
392 * Wakes up one thread waiting on a condition variable, if any.
393 * @param p_condvar condition variable
395 void vlc_cond_signal (vlc_cond_t *p_condvar)
397 #if defined(LIBVLC_USE_PTHREAD)
398 int val = pthread_cond_signal( p_condvar );
399 VLC_THREAD_ASSERT ("signaling condition variable");
401 #elif defined( WIN32 )
402 /* NOTE: This will cause a broadcast, that is wrong.
403 * This will also wake up the next waiting thread if no thread are yet
404 * waiting, which is also wrong. However both of these issues are allowed
405 * by the provision for spurious wakeups. Better have too many wakeups
406 * than too few (= deadlocks). */
407 SetEvent (*p_condvar);
413 * Wakes up all threads (if any) waiting on a condition variable.
414 * @param p_cond condition variable
416 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
418 #if defined (LIBVLC_USE_PTHREAD)
419 pthread_cond_broadcast (p_condvar);
421 #elif defined (WIN32)
422 SetEvent (*p_condvar);
429 # define WaitForMultipleObjectsEx(a,b,c) WaitForMultipleObjects(a,b)
433 * Waits for a condition variable. The calling thread will be suspended until
434 * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
435 * condition variable, the thread is cancelled with vlc_cancel(), or the
436 * system causes a "spurious" unsolicited wake-up.
438 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
439 * a recursive mutex. Although it is possible to use the same mutex for
440 * multiple condition, it is not valid to use different mutexes for the same
441 * condition variable at the same time from different threads.
443 * In case of thread cancellation, the mutex is always locked before
444 * cancellation proceeds.
446 * The canonical way to use a condition variable to wait for event foobar is:
448 vlc_mutex_lock (&lock);
449 mutex_cleanup_push (&lock); // release the mutex in case of cancellation
452 vlc_cond_wait (&wait, &lock);
454 --- foobar is now true, do something about it here --
456 vlc_cleanup_run (); // release the mutex
459 * @param p_condvar condition variable to wait on
460 * @param p_mutex mutex which is unlocked while waiting,
461 * then locked again when waking up.
462 * @param deadline <b>absolute</b> timeout
464 * @return 0 if the condition was signaled, an error code in case of timeout.
466 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
468 #if defined(LIBVLC_USE_PTHREAD)
469 int val = pthread_cond_wait( p_condvar, p_mutex );
470 VLC_THREAD_ASSERT ("waiting on condition");
472 #elif defined( WIN32 )
478 LeaveCriticalSection (&p_mutex->mutex);
479 result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
480 EnterCriticalSection (&p_mutex->mutex);
482 while (result == WAIT_IO_COMPLETION);
484 ResetEvent (*p_condvar);
490 * Waits for a condition variable up to a certain date.
491 * This works like vlc_cond_wait(), except for the additional timeout.
493 * @param p_condvar condition variable to wait on
494 * @param p_mutex mutex which is unlocked while waiting,
495 * then locked again when waking up.
496 * @param deadline <b>absolute</b> timeout
498 * @return 0 if the condition was signaled, an error code in case of timeout.
500 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
503 #if defined(LIBVLC_USE_PTHREAD)
504 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
505 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
507 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
508 if (val != ETIMEDOUT)
509 VLC_THREAD_ASSERT ("timed-waiting on condition");
512 #elif defined( WIN32 )
519 mtime_t total = (deadline - mdate ())/1000;
523 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
524 LeaveCriticalSection (&p_mutex->mutex);
525 result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
526 EnterCriticalSection (&p_mutex->mutex);
528 while (result == WAIT_IO_COMPLETION);
530 ResetEvent (*p_condvar);
532 return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
537 /*****************************************************************************
538 * vlc_tls_create: create a thread-local variable
539 *****************************************************************************/
540 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
544 #if defined( LIBVLC_USE_PTHREAD )
545 i_ret = pthread_key_create( p_tls, destr );
546 #elif defined( UNDER_CE )
548 #elif defined( WIN32 )
549 /* FIXME: remember/use the destr() callback and stop leaking whatever */
551 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
553 # error Unimplemented!
558 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
560 #if defined( LIBVLC_USE_PTHREAD )
561 pthread_key_delete (*p_tls);
562 #elif defined( UNDER_CE )
563 #elif defined( WIN32 )
566 # error Unimplemented!
570 #if defined (LIBVLC_USE_PTHREAD)
571 #elif defined (WIN32)
572 static unsigned __stdcall vlc_entry (void *data)
574 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
575 vlc_thread_t self = data;
577 vlc_threadvar_set (&cancel_key, &cancel_data);
578 self->data = self->entry (self->data);
584 * Creates and starts new thread.
586 * @param p_handle [OUT] pointer to write the handle of the created thread to
587 * @param entry entry point for the thread
588 * @param data data parameter given to the entry point
589 * @param priority thread priority value
590 * @return 0 on success, a standard error code on error.
592 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
597 #if defined( LIBVLC_USE_PTHREAD )
599 pthread_attr_init (&attr);
601 /* Block the signals that signals interface plugin handles.
602 * If the LibVLC caller wants to handle some signals by itself, it should
603 * block these before whenever invoking LibVLC. And it must obviously not
604 * start the VLC signals interface plugin.
606 * LibVLC will normally ignore any interruption caused by an asynchronous
607 * signal during a system call. But there may well be some buggy cases
608 * where it fails to handle EINTR (bug reports welcome). Some underlying
609 * libraries might also not handle EINTR properly.
615 sigdelset (&set, SIGHUP);
616 sigaddset (&set, SIGINT);
617 sigaddset (&set, SIGQUIT);
618 sigaddset (&set, SIGTERM);
620 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
621 pthread_sigmask (SIG_BLOCK, &set, &oldset);
624 struct sched_param sp = { .sched_priority = priority, };
627 if (sp.sched_priority <= 0)
628 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
630 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
632 pthread_attr_setschedpolicy (&attr, policy);
633 pthread_attr_setschedparam (&attr, &sp);
636 /* The thread stack size.
637 * The lower the value, the less address space per thread, the highest
638 * maximum simultaneous threads per process. Too low values will cause
639 * stack overflows and weird crashes. Set with caution. Also keep in mind
640 * that 64-bits platforms consume more stack than 32-bits one.
642 * Thanks to on-demand paging, thread stack size only affects address space
643 * consumption. In terms of memory, threads only use what they need
644 * (rounded up to the page boundary).
646 * For example, on Linux i386, the default is 2 mega-bytes, which supports
647 * about 320 threads per processes. */
648 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
651 ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
652 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
655 ret = pthread_create (p_handle, &attr, entry, data);
656 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
657 pthread_attr_destroy (&attr);
659 #elif defined( WIN32 ) || defined( UNDER_CE )
660 /* When using the MSVCRT C library you have to use the _beginthreadex
661 * function instead of CreateThread, otherwise you'll end up with
662 * memory leaks and the signal functions not working (see Microsoft
663 * Knowledge Base, article 104641) */
665 vlc_thread_t th = malloc (sizeof (*th));
672 #if defined( UNDER_CE )
673 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
675 hThread = (HANDLE)(uintptr_t)
676 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
681 /* Thread closes the handle when exiting, duplicate it here
682 * to be on the safe side when joining. */
683 if (!DuplicateHandle (GetCurrentProcess (), hThread,
684 GetCurrentProcess (), &th->handle, 0, FALSE,
685 DUPLICATE_SAME_ACCESS))
687 CloseHandle (hThread);
692 ResumeThread (hThread);
694 SetThreadPriority (hThread, priority);
710 /* APC procedure for thread cancellation */
711 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
714 vlc_control_cancel (VLC_DO_CANCEL);
719 * Marks a thread as cancelled. Next time the target thread reaches a
720 * cancellation point (while not having disabled cancellation), it will
721 * run its cancellation cleanup handler, the thread variable destructors, and
722 * terminate. vlc_join() must be used afterward regardless of a thread being
725 void vlc_cancel (vlc_thread_t thread_id)
727 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
728 pthread_cancel (thread_id);
729 #elif defined (WIN32)
730 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
732 # warning vlc_cancel is not implemented!
737 * Waits for a thread to complete (if needed), and destroys it.
738 * This is a cancellation point; in case of cancellation, the join does _not_
741 * @param handle thread handle
742 * @param p_result [OUT] pointer to write the thread return value or NULL
743 * @return 0 on success, a standard error code otherwise.
745 void vlc_join (vlc_thread_t handle, void **result)
747 #if defined( LIBVLC_USE_PTHREAD )
748 int val = pthread_join (handle, result);
750 vlc_thread_fatal ("joining thread", val, __func__, __FILE__, __LINE__);
752 #elif defined( UNDER_CE ) || defined( WIN32 )
755 while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
756 == WAIT_IO_COMPLETION);
758 CloseHandle (handle->handle);
760 *result = handle->data;
767 struct vlc_thread_boot
769 void * (*entry) (vlc_object_t *);
770 vlc_object_t *object;
773 static void *thread_entry (void *data)
775 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
776 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
779 msg_Dbg (obj, "thread started");
781 msg_Dbg (obj, "thread ended");
786 /*****************************************************************************
787 * vlc_thread_create: create a thread, inner version
788 *****************************************************************************
789 * Note that i_priority is only taken into account on platforms supporting
790 * userland real-time priority threads.
791 *****************************************************************************/
792 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
793 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
794 int i_priority, bool b_wait )
797 vlc_object_internals_t *p_priv = vlc_internals( p_this );
799 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
803 boot->object = p_this;
805 vlc_object_lock( p_this );
807 /* Make sure we don't re-create a thread if the object has already one */
808 assert( !p_priv->b_thread );
810 #if defined( LIBVLC_USE_PTHREAD )
812 if( config_GetInt( p_this, "rt-priority" ) > 0 )
815 /* Hack to avoid error msg */
816 if( config_GetType( p_this, "rt-offset" ) )
817 i_priority += config_GetInt( p_this, "rt-offset" );
821 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
826 msg_Dbg( p_this, "waiting for thread initialization" );
827 vlc_object_wait( p_this );
830 p_priv->b_thread = true;
831 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
832 (unsigned long)p_priv->thread_id, psz_name, i_priority,
838 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
839 psz_name, psz_file, i_line );
842 vlc_object_unlock( p_this );
846 /*****************************************************************************
847 * vlc_thread_set_priority: set the priority of the current thread when we
848 * couldn't set it in vlc_thread_create (for instance for the main thread)
849 *****************************************************************************/
850 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
851 int i_line, int i_priority )
853 vlc_object_internals_t *p_priv = vlc_internals( p_this );
855 if( !p_priv->b_thread )
857 msg_Err( p_this, "couldn't set priority of non-existent thread" );
861 #if defined( LIBVLC_USE_PTHREAD )
863 if( config_GetInt( p_this, "rt-priority" ) > 0 )
866 int i_error, i_policy;
867 struct sched_param param;
869 memset( ¶m, 0, sizeof(struct sched_param) );
870 if( config_GetType( p_this, "rt-offset" ) )
871 i_priority += config_GetInt( p_this, "rt-offset" );
872 if( i_priority <= 0 )
874 param.sched_priority = (-1) * i_priority;
875 i_policy = SCHED_OTHER;
879 param.sched_priority = i_priority;
882 if( (i_error = pthread_setschedparam( p_priv->thread_id,
883 i_policy, ¶m )) )
886 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
892 #elif defined( WIN32 ) || defined( UNDER_CE )
893 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
895 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
897 msg_Warn( p_this, "couldn't set a faster priority" );
906 /*****************************************************************************
907 * vlc_thread_join: wait until a thread exits, inner version
908 *****************************************************************************/
909 void __vlc_thread_join( vlc_object_t *p_this )
911 vlc_object_internals_t *p_priv = vlc_internals( p_this );
913 #if defined( LIBVLC_USE_PTHREAD )
914 vlc_join (p_priv->thread_id, NULL);
916 #elif defined( UNDER_CE ) || defined( WIN32 )
918 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
919 int64_t real_time, kernel_time, user_time;
921 if( ! DuplicateHandle(GetCurrentProcess(),
922 p_priv->thread_id->handle,
927 DUPLICATE_SAME_ACCESS) )
929 p_priv->b_thread = false;
930 return; /* We have a problem! */
933 vlc_join( p_priv->thread_id, NULL );
935 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
938 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
939 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
943 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
944 kernel_ft.dwLowDateTime) / 10;
947 ((((int64_t)user_ft.dwHighDateTime)<<32)|
948 user_ft.dwLowDateTime) / 10;
950 msg_Dbg( p_this, "thread times: "
951 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
952 real_time/60/1000000,
953 (double)((real_time%(60*1000000))/1000000.0),
954 kernel_time/60/1000000,
955 (double)((kernel_time%(60*1000000))/1000000.0),
956 user_time/60/1000000,
957 (double)((user_time%(60*1000000))/1000000.0) );
959 CloseHandle( hThread );
962 vlc_join( p_priv->thread_id, NULL );
966 p_priv->b_thread = false;
969 void vlc_thread_cancel (vlc_object_t *obj)
971 vlc_object_internals_t *priv = vlc_internals (obj);
974 vlc_cancel (priv->thread_id);
977 void vlc_control_cancel (int cmd, ...)
979 /* NOTE: This function only modifies thread-specific data, so there is no
980 * need to lock anything. */
981 #ifdef LIBVLC_USE_PTHREAD_CANCEL
987 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
991 /* Main thread - cannot be cancelled anyway */
994 nfo = malloc (sizeof (*nfo));
996 return; /* Uho! Expect problems! */
997 *nfo = VLC_CANCEL_INIT;
998 vlc_threadvar_set (&cancel_key, nfo);
1005 case VLC_SAVE_CANCEL:
1007 int *p_state = va_arg (ap, int *);
1008 *p_state = nfo->killable;
1009 nfo->killable = false;
1013 case VLC_RESTORE_CANCEL:
1015 int state = va_arg (ap, int);
1016 nfo->killable = state != 0;
1020 case VLC_TEST_CANCEL:
1021 if (nfo->killable && nfo->killed)
1023 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
1028 #if defined (LIBVLC_USE_PTHREAD)
1029 pthread_exit (PTHREAD_CANCELLED);
1030 #elif defined (UNDER_CE)
1032 #elif defined (WIN32)
1035 # error Not implemented!
1044 case VLC_CLEANUP_PUSH:
1046 /* cleaner is a pointer to the caller stack, no need to allocate
1047 * and copy anything. As a nice side effect, this cannot fail. */
1048 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
1049 cleaner->next = nfo->cleaners;
1050 nfo->cleaners = cleaner;
1054 case VLC_CLEANUP_POP:
1056 nfo->cleaners = nfo->cleaners->next;
1065 #undef var_AcquireMutex
1067 * Finds a process-wide mutex, creates it if needed, and locks it.
1068 * Unlock with vlc_mutex_unlock().
1069 * FIXME: This is very inefficient, this is not memory-safe and this leaks
1070 * memory. Use static locks instead.
1072 vlc_mutex_t *var_AcquireMutex( const char *name )
1076 vlc_mutex_lock (&named_mutexes.lock);
1077 lock = vlc_dictionary_value_for_key (&named_mutexes.list, name);
1078 if (lock == kVLCDictionaryNotFound)
1080 lock = malloc (sizeof (*lock));
1081 vlc_mutex_init (lock);
1082 vlc_dictionary_insert (&named_mutexes.list, name, lock);
1084 vlc_mutex_unlock (&named_mutexes.lock);
1086 vlc_mutex_lock (lock);