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 InitializeCriticalSection (&p_mutex->mutex);
251 p_mutex->recursive = false;
257 /*****************************************************************************
258 * vlc_mutex_init: initialize a recursive mutex (Do not use)
259 *****************************************************************************/
260 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
262 #if defined( LIBVLC_USE_PTHREAD )
263 pthread_mutexattr_t attr;
266 pthread_mutexattr_init( &attr );
267 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
268 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
270 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
272 i_result = pthread_mutex_init( p_mutex, &attr );
273 pthread_mutexattr_destroy( &attr );
276 #elif defined( WIN32 )
277 InitializeCriticalSection( &p_mutex->mutex );
278 p_mutex->owner = 0; /* the error value for GetThreadId()! */
279 p_mutex->recursion = 0;
280 p_mutex->recursive = true;
288 * Destroys a mutex. The mutex must not be locked.
290 * @param p_mutex mutex to destroy
291 * @return always succeeds
293 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
295 #if defined( LIBVLC_USE_PTHREAD )
296 int val = pthread_mutex_destroy( p_mutex );
297 VLC_THREAD_ASSERT ("destroying mutex");
299 #elif defined( WIN32 )
300 DeleteCriticalSection (&p_mutex->mutex);
306 * Acquires a mutex. If needed, waits for any other thread to release it.
307 * Beware of deadlocks when locking multiple mutexes at the same time,
308 * or when using mutexes from callbacks.
310 * @param p_mutex mutex initialized with vlc_mutex_init() or
311 * vlc_mutex_init_recursive()
313 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
315 #if defined(LIBVLC_USE_PTHREAD)
316 int val = pthread_mutex_lock( p_mutex );
317 VLC_THREAD_ASSERT ("locking mutex");
319 #elif defined( WIN32 )
320 if (p_mutex->recursive)
322 DWORD self = GetCurrentThreadId ();
324 if ((DWORD)InterlockedCompareExchange (&p_mutex->owner, self,
326 { /* We already locked this recursive mutex */
327 p_mutex->recursion++;
331 /* We need to lock this recursive mutex */
332 EnterCriticalSection (&p_mutex->mutex);
333 self = InterlockedExchange (&p_mutex->owner, self);
334 assert (self == 0); /* no previous owner */
337 /* Non-recursive mutex */
338 EnterCriticalSection (&p_mutex->mutex);
345 * Releases a mutex (or crashes if the mutex is not locked by the caller).
346 * @param p_mutex mutex locked with vlc_mutex_lock().
348 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
350 #if defined(LIBVLC_USE_PTHREAD)
351 int val = pthread_mutex_unlock( p_mutex );
352 VLC_THREAD_ASSERT ("unlocking mutex");
354 #elif defined( WIN32 )
355 if (p_mutex->recursive)
357 if (p_mutex->recursion != 0)
359 p_mutex->recursion--;
360 return; /* We still own this mutex */
363 /* We release the mutex */
364 InterlockedExchange (&p_mutex->owner, 0);
367 LeaveCriticalSection (&p_mutex->mutex);
372 /*****************************************************************************
373 * vlc_cond_init: initialize a condition variable
374 *****************************************************************************/
375 int vlc_cond_init( vlc_cond_t *p_condvar )
377 #if defined( LIBVLC_USE_PTHREAD )
378 pthread_condattr_t attr;
381 ret = pthread_condattr_init (&attr);
385 # if !defined (_POSIX_CLOCK_SELECTION)
386 /* Fairly outdated POSIX support (that was defined in 2001) */
387 # define _POSIX_CLOCK_SELECTION (-1)
389 # if (_POSIX_CLOCK_SELECTION >= 0)
390 /* NOTE: This must be the same clock as the one in mtime.c */
391 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
394 ret = pthread_cond_init (p_condvar, &attr);
395 pthread_condattr_destroy (&attr);
398 #elif defined( WIN32 )
399 /* Create a manual-reset event (manual reset is needed for broadcast). */
400 *p_condvar = CreateEvent( NULL, TRUE, FALSE, NULL );
401 return *p_condvar ? 0 : ENOMEM;
407 * Destroys a condition variable. No threads shall be waiting or signaling the
409 * @param p_condvar condition variable to destroy
411 void vlc_cond_destroy (vlc_cond_t *p_condvar)
413 #if defined( LIBVLC_USE_PTHREAD )
414 int val = pthread_cond_destroy( p_condvar );
415 VLC_THREAD_ASSERT ("destroying condition");
417 #elif defined( WIN32 )
418 CloseHandle( *p_condvar );
424 * Wakes up one thread waiting on a condition variable, if any.
425 * @param p_condvar condition variable
427 void vlc_cond_signal (vlc_cond_t *p_condvar)
429 #if defined(LIBVLC_USE_PTHREAD)
430 int val = pthread_cond_signal( p_condvar );
431 VLC_THREAD_ASSERT ("signaling condition variable");
433 #elif defined( WIN32 )
434 /* NOTE: This will cause a broadcast, that is wrong.
435 * This will also wake up the next waiting thread if no thread are yet
436 * waiting, which is also wrong. However both of these issues are allowed
437 * by the provision for spurious wakeups. Better have too many wakeups
438 * than too few (= deadlocks). */
439 SetEvent (*p_condvar);
445 * Wakes up all threads (if any) waiting on a condition variable.
446 * @param p_cond condition variable
448 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
450 #if defined (LIBVLC_USE_PTHREAD)
451 pthread_cond_broadcast (p_condvar);
453 #elif defined (WIN32)
454 SetEvent (*p_condvar);
461 # define WaitForMultipleObjectsEx(a,b,c) WaitForMultipleObjects(a,b)
465 * Waits for a condition variable. The calling thread will be suspended until
466 * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
467 * condition variable, the thread is cancelled with vlc_cancel(), or the
468 * system causes a "spurious" unsolicited wake-up.
470 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
471 * a recursive mutex. Although it is possible to use the same mutex for
472 * multiple condition, it is not valid to use different mutexes for the same
473 * condition variable at the same time from different threads.
475 * In case of thread cancellation, the mutex is always locked before
476 * cancellation proceeds.
478 * The canonical way to use a condition variable to wait for event foobar is:
480 vlc_mutex_lock (&lock);
481 mutex_cleanup_push (&lock); // release the mutex in case of cancellation
484 vlc_cond_wait (&wait, &lock);
486 --- foobar is now true, do something about it here --
488 vlc_cleanup_run (); // release the mutex
491 * @param p_condvar condition variable to wait on
492 * @param p_mutex mutex which is unlocked while waiting,
493 * then locked again when waking up.
494 * @param deadline <b>absolute</b> timeout
496 * @return 0 if the condition was signaled, an error code in case of timeout.
498 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
500 #if defined(LIBVLC_USE_PTHREAD)
501 int val = pthread_cond_wait( p_condvar, p_mutex );
502 VLC_THREAD_ASSERT ("waiting on condition");
504 #elif defined( WIN32 )
507 assert (!p_mutex->recursive);
511 LeaveCriticalSection (&p_mutex->mutex);
512 result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
513 EnterCriticalSection (&p_mutex->mutex);
515 while (result == WAIT_IO_COMPLETION);
517 ResetEvent (*p_condvar);
523 * Waits for a condition variable up to a certain date.
524 * This works like vlc_cond_wait(), except for the additional timeout.
526 * @param p_condvar condition variable to wait on
527 * @param p_mutex mutex which is unlocked while waiting,
528 * then locked again when waking up.
529 * @param deadline <b>absolute</b> timeout
531 * @return 0 if the condition was signaled, an error code in case of timeout.
533 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
536 #if defined(LIBVLC_USE_PTHREAD)
537 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
538 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
540 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
541 if (val != ETIMEDOUT)
542 VLC_THREAD_ASSERT ("timed-waiting on condition");
545 #elif defined( WIN32 )
548 assert (!p_mutex->recursive);
553 mtime_t total = (deadline - mdate ())/1000;
557 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
558 LeaveCriticalSection (&p_mutex->mutex);
559 result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
560 EnterCriticalSection (&p_mutex->mutex);
562 while (result == WAIT_IO_COMPLETION);
564 ResetEvent (*p_condvar);
566 return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
571 /*****************************************************************************
572 * vlc_tls_create: create a thread-local variable
573 *****************************************************************************/
574 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
578 #if defined( LIBVLC_USE_PTHREAD )
579 i_ret = pthread_key_create( p_tls, destr );
580 #elif defined( UNDER_CE )
582 #elif defined( WIN32 )
583 /* FIXME: remember/use the destr() callback and stop leaking whatever */
585 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
587 # error Unimplemented!
592 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
594 #if defined( LIBVLC_USE_PTHREAD )
595 pthread_key_delete (*p_tls);
596 #elif defined( UNDER_CE )
597 #elif defined( WIN32 )
600 # error Unimplemented!
604 #if defined (LIBVLC_USE_PTHREAD)
605 #elif defined (WIN32)
606 static unsigned __stdcall vlc_entry (void *data)
608 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
609 vlc_thread_t self = data;
611 vlc_threadvar_set (&cancel_key, &cancel_data);
612 self->data = self->entry (self->data);
618 * Creates and starts new thread.
620 * @param p_handle [OUT] pointer to write the handle of the created thread to
621 * @param entry entry point for the thread
622 * @param data data parameter given to the entry point
623 * @param priority thread priority value
624 * @return 0 on success, a standard error code on error.
626 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
631 #if defined( LIBVLC_USE_PTHREAD )
633 pthread_attr_init (&attr);
635 /* Block the signals that signals interface plugin handles.
636 * If the LibVLC caller wants to handle some signals by itself, it should
637 * block these before whenever invoking LibVLC. And it must obviously not
638 * start the VLC signals interface plugin.
640 * LibVLC will normally ignore any interruption caused by an asynchronous
641 * signal during a system call. But there may well be some buggy cases
642 * where it fails to handle EINTR (bug reports welcome). Some underlying
643 * libraries might also not handle EINTR properly.
649 sigdelset (&set, SIGHUP);
650 sigaddset (&set, SIGINT);
651 sigaddset (&set, SIGQUIT);
652 sigaddset (&set, SIGTERM);
654 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
655 pthread_sigmask (SIG_BLOCK, &set, &oldset);
658 struct sched_param sp = { .sched_priority = priority, };
661 if (sp.sched_priority <= 0)
662 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
664 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
666 pthread_attr_setschedpolicy (&attr, policy);
667 pthread_attr_setschedparam (&attr, &sp);
670 /* The thread stack size.
671 * The lower the value, the less address space per thread, the highest
672 * maximum simultaneous threads per process. Too low values will cause
673 * stack overflows and weird crashes. Set with caution. Also keep in mind
674 * that 64-bits platforms consume more stack than 32-bits one.
676 * Thanks to on-demand paging, thread stack size only affects address space
677 * consumption. In terms of memory, threads only use what they need
678 * (rounded up to the page boundary).
680 * For example, on Linux i386, the default is 2 mega-bytes, which supports
681 * about 320 threads per processes. */
682 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
685 ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
686 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
689 ret = pthread_create (p_handle, &attr, entry, data);
690 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
691 pthread_attr_destroy (&attr);
693 #elif defined( WIN32 ) || defined( UNDER_CE )
694 /* When using the MSVCRT C library you have to use the _beginthreadex
695 * function instead of CreateThread, otherwise you'll end up with
696 * memory leaks and the signal functions not working (see Microsoft
697 * Knowledge Base, article 104641) */
699 vlc_thread_t th = malloc (sizeof (*th));
706 #if defined( UNDER_CE )
707 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
709 hThread = (HANDLE)(uintptr_t)
710 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
715 /* Thread closes the handle when exiting, duplicate it here
716 * to be on the safe side when joining. */
717 if (!DuplicateHandle (GetCurrentProcess (), hThread,
718 GetCurrentProcess (), &th->handle, 0, FALSE,
719 DUPLICATE_SAME_ACCESS))
721 CloseHandle (hThread);
726 ResumeThread (hThread);
728 SetThreadPriority (hThread, priority);
744 /* APC procedure for thread cancellation */
745 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
748 vlc_control_cancel (VLC_DO_CANCEL);
753 * Marks a thread as cancelled. Next time the target thread reaches a
754 * cancellation point (while not having disabled cancellation), it will
755 * run its cancellation cleanup handler, the thread variable destructors, and
756 * terminate. vlc_join() must be used afterward regardless of a thread being
759 void vlc_cancel (vlc_thread_t thread_id)
761 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
762 pthread_cancel (thread_id);
763 #elif defined (WIN32)
764 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
766 # warning vlc_cancel is not implemented!
771 * Waits for a thread to complete (if needed), and destroys it.
772 * This is a cancellation point; in case of cancellation, the join does _not_
775 * @param handle thread handle
776 * @param p_result [OUT] pointer to write the thread return value or NULL
777 * @return 0 on success, a standard error code otherwise.
779 void vlc_join (vlc_thread_t handle, void **result)
781 #if defined( LIBVLC_USE_PTHREAD )
782 int val = pthread_join (handle, result);
784 vlc_thread_fatal ("joining thread", val, __func__, __FILE__, __LINE__);
786 #elif defined( UNDER_CE ) || defined( WIN32 )
789 while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
790 == WAIT_IO_COMPLETION);
792 CloseHandle (handle->handle);
794 *result = handle->data;
801 struct vlc_thread_boot
803 void * (*entry) (vlc_object_t *);
804 vlc_object_t *object;
807 static void *thread_entry (void *data)
809 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
810 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
813 msg_Dbg (obj, "thread started");
815 msg_Dbg (obj, "thread ended");
820 /*****************************************************************************
821 * vlc_thread_create: create a thread, inner version
822 *****************************************************************************
823 * Note that i_priority is only taken into account on platforms supporting
824 * userland real-time priority threads.
825 *****************************************************************************/
826 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
827 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
828 int i_priority, bool b_wait )
831 vlc_object_internals_t *p_priv = vlc_internals( p_this );
833 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
837 boot->object = p_this;
839 vlc_object_lock( p_this );
841 /* Make sure we don't re-create a thread if the object has already one */
842 assert( !p_priv->b_thread );
844 #if defined( LIBVLC_USE_PTHREAD )
846 if( config_GetInt( p_this, "rt-priority" ) > 0 )
849 /* Hack to avoid error msg */
850 if( config_GetType( p_this, "rt-offset" ) )
851 i_priority += config_GetInt( p_this, "rt-offset" );
855 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
860 msg_Dbg( p_this, "waiting for thread initialization" );
861 vlc_object_wait( p_this );
864 p_priv->b_thread = true;
865 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
866 (unsigned long)p_priv->thread_id, psz_name, i_priority,
872 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
873 psz_name, psz_file, i_line );
876 vlc_object_unlock( p_this );
880 /*****************************************************************************
881 * vlc_thread_set_priority: set the priority of the current thread when we
882 * couldn't set it in vlc_thread_create (for instance for the main thread)
883 *****************************************************************************/
884 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
885 int i_line, int i_priority )
887 vlc_object_internals_t *p_priv = vlc_internals( p_this );
889 if( !p_priv->b_thread )
891 msg_Err( p_this, "couldn't set priority of non-existent thread" );
895 #if defined( LIBVLC_USE_PTHREAD )
897 if( config_GetInt( p_this, "rt-priority" ) > 0 )
900 int i_error, i_policy;
901 struct sched_param param;
903 memset( ¶m, 0, sizeof(struct sched_param) );
904 if( config_GetType( p_this, "rt-offset" ) )
905 i_priority += config_GetInt( p_this, "rt-offset" );
906 if( i_priority <= 0 )
908 param.sched_priority = (-1) * i_priority;
909 i_policy = SCHED_OTHER;
913 param.sched_priority = i_priority;
916 if( (i_error = pthread_setschedparam( p_priv->thread_id,
917 i_policy, ¶m )) )
920 msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
926 #elif defined( WIN32 ) || defined( UNDER_CE )
927 VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
929 if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
931 msg_Warn( p_this, "couldn't set a faster priority" );
940 /*****************************************************************************
941 * vlc_thread_join: wait until a thread exits, inner version
942 *****************************************************************************/
943 void __vlc_thread_join( vlc_object_t *p_this )
945 vlc_object_internals_t *p_priv = vlc_internals( p_this );
947 #if defined( LIBVLC_USE_PTHREAD )
948 vlc_join (p_priv->thread_id, NULL);
950 #elif defined( UNDER_CE ) || defined( WIN32 )
952 FILETIME create_ft, exit_ft, kernel_ft, user_ft;
953 int64_t real_time, kernel_time, user_time;
955 if( ! DuplicateHandle(GetCurrentProcess(),
956 p_priv->thread_id->handle,
961 DUPLICATE_SAME_ACCESS) )
963 p_priv->b_thread = false;
964 return; /* We have a problem! */
967 vlc_join( p_priv->thread_id, NULL );
969 if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
972 ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
973 ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
977 ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
978 kernel_ft.dwLowDateTime) / 10;
981 ((((int64_t)user_ft.dwHighDateTime)<<32)|
982 user_ft.dwLowDateTime) / 10;
984 msg_Dbg( p_this, "thread times: "
985 "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
986 real_time/60/1000000,
987 (double)((real_time%(60*1000000))/1000000.0),
988 kernel_time/60/1000000,
989 (double)((kernel_time%(60*1000000))/1000000.0),
990 user_time/60/1000000,
991 (double)((user_time%(60*1000000))/1000000.0) );
993 CloseHandle( hThread );
996 vlc_join( p_priv->thread_id, NULL );
1000 p_priv->b_thread = false;
1003 void vlc_thread_cancel (vlc_object_t *obj)
1005 vlc_object_internals_t *priv = vlc_internals (obj);
1008 vlc_cancel (priv->thread_id);
1011 void vlc_control_cancel (int cmd, ...)
1013 /* NOTE: This function only modifies thread-specific data, so there is no
1014 * need to lock anything. */
1015 #ifdef LIBVLC_USE_PTHREAD_CANCEL
1021 vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
1025 /* Main thread - cannot be cancelled anyway */
1028 nfo = malloc (sizeof (*nfo));
1030 return; /* Uho! Expect problems! */
1031 *nfo = VLC_CANCEL_INIT;
1032 vlc_threadvar_set (&cancel_key, nfo);
1039 case VLC_SAVE_CANCEL:
1041 int *p_state = va_arg (ap, int *);
1042 *p_state = nfo->killable;
1043 nfo->killable = false;
1047 case VLC_RESTORE_CANCEL:
1049 int state = va_arg (ap, int);
1050 nfo->killable = state != 0;
1054 case VLC_TEST_CANCEL:
1055 if (nfo->killable && nfo->killed)
1057 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
1062 #if defined (LIBVLC_USE_PTHREAD)
1063 pthread_exit (PTHREAD_CANCELLED);
1064 #elif defined (UNDER_CE)
1066 #elif defined (WIN32)
1069 # error Not implemented!
1078 case VLC_CLEANUP_PUSH:
1080 /* cleaner is a pointer to the caller stack, no need to allocate
1081 * and copy anything. As a nice side effect, this cannot fail. */
1082 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
1083 cleaner->next = nfo->cleaners;
1084 nfo->cleaners = cleaner;
1088 case VLC_CLEANUP_POP:
1090 nfo->cleaners = nfo->cleaners->next;
1099 #undef var_AcquireMutex
1101 * Finds a process-wide mutex, creates it if needed, and locks it.
1102 * Unlock with vlc_mutex_unlock().
1103 * FIXME: This is very inefficient, this is not memory-safe and this leaks
1104 * memory. Use static locks instead.
1106 vlc_mutex_t *var_AcquireMutex( const char *name )
1110 vlc_mutex_lock (&named_mutexes.lock);
1111 lock = vlc_dictionary_value_for_key (&named_mutexes.list, name);
1112 if (lock == kVLCDictionaryNotFound)
1114 lock = malloc (sizeof (*lock));
1115 vlc_mutex_init (lock);
1116 vlc_dictionary_insert (&named_mutexes.list, name, lock);
1118 vlc_mutex_unlock (&named_mutexes.lock);
1120 vlc_mutex_lock (lock);