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;
50 vlc_dictionary_t list;
54 #ifdef LIBVLC_USE_PTHREAD
55 PTHREAD_MUTEX_INITIALIZER,
59 #ifdef HAVE_EXECINFO_H
60 # include <execinfo.h>
64 * Print a backtrace to the standard error for debugging purpose.
66 void vlc_trace (const char *fn, const char *file, unsigned line)
68 fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
69 fflush (stderr); /* needed before switch to low-level I/O */
72 int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
73 backtrace_symbols_fd (stack, len, 2);
80 static inline unsigned long vlc_threadid (void)
82 #if defined(LIBVLC_USE_PTHREAD)
83 union { pthread_t th; unsigned long int i; } v = { };
84 v.th = pthread_self ();
88 return GetCurrentThreadId ();
96 /*****************************************************************************
97 * vlc_thread_fatal: Report an error from the threading layer
98 *****************************************************************************
99 * This is mostly meant for debugging.
100 *****************************************************************************/
102 vlc_thread_fatal (const char *action, int error,
103 const char *function, const char *file, unsigned line)
105 fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
106 action, error, vlc_threadid ());
107 vlc_trace (function, file, line);
109 /* Sometimes strerror_r() crashes too, so make sure we print an error
110 * message before we invoke it */
112 /* Avoid the strerror_r() prototype brain damage in glibc */
114 fprintf (stderr, " Error message: %m\n");
115 #elif !defined (WIN32)
119 switch (strerror_r (error, buf, sizeof (buf)))
124 case ERANGE: /* should never happen */
125 msg = "unknwon (too big to display)";
128 msg = "unknown (invalid error number)";
131 fprintf (stderr, " Error message: %s\n", msg);
139 # define VLC_THREAD_ASSERT( action ) \
140 if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
142 # define VLC_THREAD_ASSERT( action ) ((void)val)
146 * Per-thread cancellation data
148 #ifndef LIBVLC_USE_PTHREAD_CANCEL
149 typedef struct vlc_cancel_t
151 vlc_cleanup_t *cleaners;
156 # define VLC_CANCEL_INIT { NULL, true, false }
160 static vlc_mutex_t super_mutex;
162 BOOL WINAPI DllMain (HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvReserved)
169 case DLL_PROCESS_ATTACH:
170 vlc_dictionary_init (&named_mutexes.list, 0);
171 vlc_mutex_init (&named_mutexes.lock);
172 vlc_mutex_init (&super_mutex);
173 vlc_threadvar_create (&cancel_key, free);
176 case DLL_PROCESS_DETACH:
177 vlc_threadvar_delete( &cancel_key );
178 vlc_mutex_destroy (&super_mutex);
179 vlc_mutex_destroy (&named_mutexes.lock);
180 vlc_dictionary_clear (&named_mutexes.list);
187 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
188 /* This is not prototyped under glibc, though it exists. */
189 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
192 /*****************************************************************************
193 * vlc_mutex_init: initialize a mutex
194 *****************************************************************************/
195 int vlc_mutex_init( vlc_mutex_t *p_mutex )
197 #if defined( LIBVLC_USE_PTHREAD )
198 pthread_mutexattr_t attr;
201 pthread_mutexattr_init( &attr );
204 /* Create error-checking mutex to detect problems more easily. */
205 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
206 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
208 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
211 i_result = pthread_mutex_init( p_mutex, &attr );
212 pthread_mutexattr_destroy( &attr );
215 #elif defined( WIN32 )
216 /* This creates a recursive mutex. This is OK as fast mutexes have
217 * no defined behavior in case of recursive locking. */
218 InitializeCriticalSection (&p_mutex->mutex);
224 /*****************************************************************************
225 * vlc_mutex_init: initialize a recursive mutex (Do not use)
226 *****************************************************************************/
227 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
229 #if defined( LIBVLC_USE_PTHREAD )
230 pthread_mutexattr_t attr;
233 pthread_mutexattr_init( &attr );
234 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
235 pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
237 pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
239 i_result = pthread_mutex_init( p_mutex, &attr );
240 pthread_mutexattr_destroy( &attr );
243 #elif defined( WIN32 )
244 InitializeCriticalSection( &p_mutex->mutex );
245 InterlockedIncrement (&p_mutex->initialized);
254 * Destroys a mutex. The mutex must not be locked.
256 * @param p_mutex mutex to destroy
257 * @return always succeeds
259 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
261 #if defined( LIBVLC_USE_PTHREAD )
262 int val = pthread_mutex_destroy( p_mutex );
263 VLC_THREAD_ASSERT ("destroying mutex");
265 #elif defined( WIN32 )
266 InterlockedDecrement (&p_mutex->initialized);
267 DeleteCriticalSection (&p_mutex->mutex);
273 * Acquires a mutex. If needed, waits for any other thread to release it.
274 * Beware of deadlocks when locking multiple mutexes at the same time,
275 * or when using mutexes from callbacks.
277 * @param p_mutex mutex initialized with vlc_mutex_init() or
278 * vlc_mutex_init_recursive()
280 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
282 #if defined(LIBVLC_USE_PTHREAD)
283 int val = pthread_mutex_lock( p_mutex );
284 VLC_THREAD_ASSERT ("locking mutex");
286 #elif defined( WIN32 )
287 if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
288 { /* ^^ We could also lock super_mutex all the time... sluggish */
289 assert (p_mutex != &super_mutex); /* this one cannot be static */
291 vlc_mutex_lock (&super_mutex);
292 vlc_mutex_init (p_mutex);
293 /* FIXME: destroy the mutex some time... */
294 vlc_mutex_unlock (&super_mutex);
296 EnterCriticalSection (&p_mutex->mutex);
303 * Releases a mutex (or crashes if the mutex is not locked by the caller).
304 * @param p_mutex mutex locked with vlc_mutex_lock().
306 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
308 #if defined(LIBVLC_USE_PTHREAD)
309 int val = pthread_mutex_unlock( p_mutex );
310 VLC_THREAD_ASSERT ("unlocking mutex");
312 #elif defined( WIN32 )
313 LeaveCriticalSection (&p_mutex->mutex);
318 /*****************************************************************************
319 * vlc_cond_init: initialize a condition variable
320 *****************************************************************************/
321 int vlc_cond_init( vlc_cond_t *p_condvar )
323 #if defined( LIBVLC_USE_PTHREAD )
324 pthread_condattr_t attr;
327 ret = pthread_condattr_init (&attr);
331 # if !defined (_POSIX_CLOCK_SELECTION)
332 /* Fairly outdated POSIX support (that was defined in 2001) */
333 # define _POSIX_CLOCK_SELECTION (-1)
335 # if (_POSIX_CLOCK_SELECTION >= 0)
336 /* NOTE: This must be the same clock as the one in mtime.c */
337 pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
340 ret = pthread_cond_init (p_condvar, &attr);
341 pthread_condattr_destroy (&attr);
344 #elif defined( WIN32 )
345 /* Create a manual-reset event (manual reset is needed for broadcast). */
346 *p_condvar = CreateEvent( NULL, TRUE, FALSE, NULL );
347 return *p_condvar ? 0 : ENOMEM;
353 * Destroys a condition variable. No threads shall be waiting or signaling the
355 * @param p_condvar condition variable to destroy
357 void vlc_cond_destroy (vlc_cond_t *p_condvar)
359 #if defined( LIBVLC_USE_PTHREAD )
360 int val = pthread_cond_destroy( p_condvar );
361 VLC_THREAD_ASSERT ("destroying condition");
363 #elif defined( WIN32 )
364 CloseHandle( *p_condvar );
370 * Wakes up one thread waiting on a condition variable, if any.
371 * @param p_condvar condition variable
373 void vlc_cond_signal (vlc_cond_t *p_condvar)
375 #if defined(LIBVLC_USE_PTHREAD)
376 int val = pthread_cond_signal( p_condvar );
377 VLC_THREAD_ASSERT ("signaling condition variable");
379 #elif defined( WIN32 )
380 /* NOTE: This will cause a broadcast, that is wrong.
381 * This will also wake up the next waiting thread if no thread are yet
382 * waiting, which is also wrong. However both of these issues are allowed
383 * by the provision for spurious wakeups. Better have too many wakeups
384 * than too few (= deadlocks). */
385 SetEvent (*p_condvar);
391 * Wakes up all threads (if any) waiting on a condition variable.
392 * @param p_cond condition variable
394 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
396 #if defined (LIBVLC_USE_PTHREAD)
397 pthread_cond_broadcast (p_condvar);
399 #elif defined (WIN32)
400 SetEvent (*p_condvar);
407 # define WaitForMultipleObjectsEx(a,b,c) WaitForMultipleObjects(a,b)
411 * Waits for a condition variable. The calling thread will be suspended until
412 * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
413 * condition variable, the thread is cancelled with vlc_cancel(), or the
414 * system causes a "spurious" unsolicited wake-up.
416 * A mutex is needed to wait on a condition variable. It must <b>not</b> be
417 * a recursive mutex. Although it is possible to use the same mutex for
418 * multiple condition, it is not valid to use different mutexes for the same
419 * condition variable at the same time from different threads.
421 * In case of thread cancellation, the mutex is always locked before
422 * cancellation proceeds.
424 * The canonical way to use a condition variable to wait for event foobar is:
426 vlc_mutex_lock (&lock);
427 mutex_cleanup_push (&lock); // release the mutex in case of cancellation
430 vlc_cond_wait (&wait, &lock);
432 --- foobar is now true, do something about it here --
434 vlc_cleanup_run (); // release the mutex
437 * @param p_condvar condition variable to wait on
438 * @param p_mutex mutex which is unlocked while waiting,
439 * then locked again when waking up.
440 * @param deadline <b>absolute</b> timeout
442 * @return 0 if the condition was signaled, an error code in case of timeout.
444 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
446 #if defined(LIBVLC_USE_PTHREAD)
447 int val = pthread_cond_wait( p_condvar, p_mutex );
448 VLC_THREAD_ASSERT ("waiting on condition");
450 #elif defined( WIN32 )
456 LeaveCriticalSection (&p_mutex->mutex);
457 result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
458 EnterCriticalSection (&p_mutex->mutex);
460 while (result == WAIT_IO_COMPLETION);
462 ResetEvent (*p_condvar);
468 * Waits for a condition variable up to a certain date.
469 * This works like vlc_cond_wait(), except for the additional timeout.
471 * @param p_condvar condition variable to wait on
472 * @param p_mutex mutex which is unlocked while waiting,
473 * then locked again when waking up.
474 * @param deadline <b>absolute</b> timeout
476 * @return 0 if the condition was signaled, an error code in case of timeout.
478 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
481 #if defined(LIBVLC_USE_PTHREAD)
482 lldiv_t d = lldiv( deadline, CLOCK_FREQ );
483 struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
485 int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
486 if (val != ETIMEDOUT)
487 VLC_THREAD_ASSERT ("timed-waiting on condition");
490 #elif defined( WIN32 )
497 mtime_t total = (deadline - mdate ())/1000;
501 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
502 LeaveCriticalSection (&p_mutex->mutex);
503 result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
504 EnterCriticalSection (&p_mutex->mutex);
506 while (result == WAIT_IO_COMPLETION);
508 ResetEvent (*p_condvar);
510 return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
515 /*****************************************************************************
516 * vlc_tls_create: create a thread-local variable
517 *****************************************************************************/
518 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
522 #if defined( LIBVLC_USE_PTHREAD )
523 i_ret = pthread_key_create( p_tls, destr );
524 #elif defined( UNDER_CE )
526 #elif defined( WIN32 )
527 /* FIXME: remember/use the destr() callback and stop leaking whatever */
529 i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
531 # error Unimplemented!
536 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
538 #if defined( LIBVLC_USE_PTHREAD )
539 pthread_key_delete (*p_tls);
540 #elif defined( UNDER_CE )
541 #elif defined( WIN32 )
544 # error Unimplemented!
548 #if defined (LIBVLC_USE_PTHREAD)
549 #elif defined (WIN32)
550 static unsigned __stdcall vlc_entry (void *data)
552 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
553 vlc_thread_t self = data;
555 vlc_threadvar_set (&cancel_key, &cancel_data);
556 self->data = self->entry (self->data);
562 * Creates and starts new thread.
564 * @param p_handle [OUT] pointer to write the handle of the created thread to
565 * @param entry entry point for the thread
566 * @param data data parameter given to the entry point
567 * @param priority thread priority value
568 * @return 0 on success, a standard error code on error.
570 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
575 #if defined( LIBVLC_USE_PTHREAD )
577 pthread_attr_init (&attr);
579 /* Block the signals that signals interface plugin handles.
580 * If the LibVLC caller wants to handle some signals by itself, it should
581 * block these before whenever invoking LibVLC. And it must obviously not
582 * start the VLC signals interface plugin.
584 * LibVLC will normally ignore any interruption caused by an asynchronous
585 * signal during a system call. But there may well be some buggy cases
586 * where it fails to handle EINTR (bug reports welcome). Some underlying
587 * libraries might also not handle EINTR properly.
593 sigdelset (&set, SIGHUP);
594 sigaddset (&set, SIGINT);
595 sigaddset (&set, SIGQUIT);
596 sigaddset (&set, SIGTERM);
598 sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
599 pthread_sigmask (SIG_BLOCK, &set, &oldset);
602 struct sched_param sp = { .sched_priority = priority, };
605 if (sp.sched_priority <= 0)
606 sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
608 sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
610 pthread_attr_setschedpolicy (&attr, policy);
611 pthread_attr_setschedparam (&attr, &sp);
614 /* The thread stack size.
615 * The lower the value, the less address space per thread, the highest
616 * maximum simultaneous threads per process. Too low values will cause
617 * stack overflows and weird crashes. Set with caution. Also keep in mind
618 * that 64-bits platforms consume more stack than 32-bits one.
620 * Thanks to on-demand paging, thread stack size only affects address space
621 * consumption. In terms of memory, threads only use what they need
622 * (rounded up to the page boundary).
624 * For example, on Linux i386, the default is 2 mega-bytes, which supports
625 * about 320 threads per processes. */
626 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
629 ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
630 assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
633 ret = pthread_create (p_handle, &attr, entry, data);
634 pthread_sigmask (SIG_SETMASK, &oldset, NULL);
635 pthread_attr_destroy (&attr);
637 #elif defined( WIN32 ) || defined( UNDER_CE )
638 /* When using the MSVCRT C library you have to use the _beginthreadex
639 * function instead of CreateThread, otherwise you'll end up with
640 * memory leaks and the signal functions not working (see Microsoft
641 * Knowledge Base, article 104641) */
643 vlc_thread_t th = malloc (sizeof (*th));
650 #if defined( UNDER_CE )
651 hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
653 hThread = (HANDLE)(uintptr_t)
654 _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
659 /* Thread closes the handle when exiting, duplicate it here
660 * to be on the safe side when joining. */
661 if (!DuplicateHandle (GetCurrentProcess (), hThread,
662 GetCurrentProcess (), &th->handle, 0, FALSE,
663 DUPLICATE_SAME_ACCESS))
665 CloseHandle (hThread);
670 ResumeThread (hThread);
672 SetThreadPriority (hThread, priority);
688 /* APC procedure for thread cancellation */
689 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
692 vlc_control_cancel (VLC_DO_CANCEL);
697 * Marks a thread as cancelled. Next time the target thread reaches a
698 * cancellation point (while not having disabled cancellation), it will
699 * run its cancellation cleanup handler, the thread variable destructors, and
700 * terminate. vlc_join() must be used afterward regardless of a thread being
703 void vlc_cancel (vlc_thread_t thread_id)
705 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
706 pthread_cancel (thread_id);
707 #elif defined (WIN32)
708 QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
710 # warning vlc_cancel is not implemented!
715 * Waits for a thread to complete (if needed), and destroys it.
716 * This is a cancellation point; in case of cancellation, the join does _not_
719 * @param handle thread handle
720 * @param p_result [OUT] pointer to write the thread return value or NULL
721 * @return 0 on success, a standard error code otherwise.
723 void vlc_join (vlc_thread_t handle, void **result)
725 #if defined( LIBVLC_USE_PTHREAD )
726 int val = pthread_join (handle, result);
728 vlc_thread_fatal ("joining thread", val, __func__, __FILE__, __LINE__);
730 #elif defined( UNDER_CE ) || defined( WIN32 )
733 while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
734 == WAIT_IO_COMPLETION);
736 CloseHandle (handle->handle);
738 *result = handle->data;
745 struct vlc_thread_boot
747 void * (*entry) (vlc_object_t *);
748 vlc_object_t *object;
751 static void *thread_entry (void *data)
753 vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
754 void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
757 msg_Dbg (obj, "thread started");
759 msg_Dbg (obj, "thread ended");
764 /*****************************************************************************
765 * vlc_thread_create: create a thread, inner version
766 *****************************************************************************
767 * Note that i_priority is only taken into account on platforms supporting
768 * userland real-time priority threads.
769 *****************************************************************************/
770 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
771 const char *psz_name, void * ( *func ) ( vlc_object_t * ),
772 int i_priority, bool b_wait )
775 vlc_object_internals_t *p_priv = vlc_internals( p_this );
777 struct vlc_thread_boot *boot = malloc (sizeof (*boot));
781 boot->object = p_this;
783 /* Make sure we don't re-create a thread if the object has already one */
784 assert( !p_priv->b_thread );
786 #if defined( LIBVLC_USE_PTHREAD )
788 sem_init (&p_priv->thread_ready, 0, 0);
790 if( config_GetInt( p_this, "rt-priority" ) > 0 )
793 /* Hack to avoid error msg */
794 if( config_GetType( p_this, "rt-offset" ) )
795 i_priority += config_GetInt( p_this, "rt-offset" );
797 #elif defined (WIN32)
799 p_priv->thread_ready = CreateEvent (NULL, TRUE, FALSE, NULL);
802 p_priv->b_thread = true;
803 i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
806 msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
807 (unsigned long)p_priv->thread_id, psz_name, i_priority,
811 msg_Dbg( p_this, "waiting for thread initialization" );
812 #if defined (LIBVLC_USE_PTHREAD)
813 sem_wait (&p_priv->thread_ready);
814 sem_destroy (&p_priv->thread_ready);
815 #elif defined (WIN32)
816 WaitForSingleObject (p_priv->thread_ready, INFINITE);
817 CloseHandle (p_priv->thread_ready);
823 p_priv->b_thread = false;
825 msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
826 psz_name, psz_file, i_line );
832 #undef vlc_thread_ready
833 void vlc_thread_ready (vlc_object_t *obj)
835 vlc_object_internals_t *priv = vlc_internals (obj);
837 assert (priv->b_thread);
838 #if defined (LIBVLC_USE_PTHREAD)
839 assert (pthread_equal (pthread_self (), priv->thread_id));
840 sem_post (&priv->thread_ready);
841 #elif defined (WIN32)
842 SetEvent (priv->thread_ready);
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);