]> git.sesse.net Git - vlc/blob - src/misc/threads.c
Get rid of p_root object
[vlc] / src / misc / threads.c
1 /*****************************************************************************
2  * threads.c : threads implementation for the VideoLAN client
3  *****************************************************************************
4  * Copyright (C) 1999-2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          Gildas Bazin <gbazin@netcourrier.com>
10  *          Clément Sténac
11  *          Rémi Denis-Courmont
12  *
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.
17  *
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.
22  *
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  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33
34 #include "libvlc.h"
35 #include <stdarg.h>
36 #include <assert.h>
37 #ifdef HAVE_UNISTD_H
38 # include <unistd.h>
39 #endif
40 #include <signal.h>
41
42 /*****************************************************************************
43  * Global mutex for lazy initialization of the threads system
44  *****************************************************************************/
45 static volatile unsigned i_initializations = 0;
46
47 #if defined( LIBVLC_USE_PTHREAD )
48 # include <sched.h>
49
50 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
51 #else
52 static vlc_threadvar_t cancel_key;
53 #endif
54
55 static struct
56 {
57    vlc_dictionary_t list;
58    vlc_mutex_t      lock;
59 } named_mutexes;
60
61 #ifdef HAVE_EXECINFO_H
62 # include <execinfo.h>
63 #endif
64
65 /**
66  * Print a backtrace to the standard error for debugging purpose.
67  */
68 void vlc_trace (const char *fn, const char *file, unsigned line)
69 {
70      fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
71      fflush (stderr); /* needed before switch to low-level I/O */
72 #ifdef HAVE_BACKTRACE
73      void *stack[20];
74      int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
75      backtrace_symbols_fd (stack, len, 2);
76 #endif
77 #ifndef WIN32
78      fsync (2);
79 #endif
80 }
81
82 static inline unsigned long vlc_threadid (void)
83 {
84 #if defined(LIBVLC_USE_PTHREAD)
85      union { pthread_t th; unsigned long int i; } v = { };
86      v.th = pthread_self ();
87      return v.i;
88
89 #elif defined (WIN32)
90      return GetCurrentThreadId ();
91
92 #else
93      return 0;
94
95 #endif
96 }
97
98 /*****************************************************************************
99  * vlc_thread_fatal: Report an error from the threading layer
100  *****************************************************************************
101  * This is mostly meant for debugging.
102  *****************************************************************************/
103 static void
104 vlc_thread_fatal (const char *action, int error,
105                   const char *function, const char *file, unsigned line)
106 {
107     fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
108              action, error, vlc_threadid ());
109     vlc_trace (function, file, line);
110
111     /* Sometimes strerror_r() crashes too, so make sure we print an error
112      * message before we invoke it */
113 #ifdef __GLIBC__
114     /* Avoid the strerror_r() prototype brain damage in glibc */
115     errno = error;
116     fprintf (stderr, " Error message: %m\n");
117 #elif !defined (WIN32)
118     char buf[1000];
119     const char *msg;
120
121     switch (strerror_r (error, buf, sizeof (buf)))
122     {
123         case 0:
124             msg = buf;
125             break;
126         case ERANGE: /* should never happen */
127             msg = "unknwon (too big to display)";
128             break;
129         default:
130             msg = "unknown (invalid error number)";
131             break;
132     }
133     fprintf (stderr, " Error message: %s\n", msg);
134 #endif
135     fflush (stderr);
136
137     abort ();
138 }
139
140 #ifndef NDEBUG
141 # define VLC_THREAD_ASSERT( action ) \
142     if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
143 #else
144 # define VLC_THREAD_ASSERT( action ) ((void)val)
145 #endif
146
147 /**
148  * Per-thread cancellation data
149  */
150 #ifndef LIBVLC_USE_PTHREAD_CANCEL
151 typedef struct vlc_cancel_t
152 {
153     vlc_cleanup_t *cleaners;
154     bool           killable;
155     bool           killed;
156 } vlc_cancel_t;
157
158 # define VLC_CANCEL_INIT { NULL, true, false }
159 #endif
160
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 )
169 {
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 );
174 #endif
175
176     if( i_initializations == 0 )
177     {
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 );
182 #endif
183     }
184     i_initializations++;
185
186 #if defined( LIBVLC_USE_PTHREAD )
187     pthread_mutex_unlock( &once_mutex );
188 #endif
189
190     return VLC_SUCCESS;
191 }
192
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 )
199 {
200 #if defined( LIBVLC_USE_PTHREAD )
201     pthread_mutex_lock( &once_mutex );
202 #endif
203
204     assert( i_initializations > 0 );
205
206     if( i_initializations == 1 )
207     {
208 #ifndef LIBVLC_USE_PTHREAD
209         vlc_threadvar_delete( &cancel_key );
210 #endif
211         vlc_mutex_destroy (&named_mutexes.lock);
212         vlc_dictionary_clear (&named_mutexes.list);
213     }
214     i_initializations--;
215
216 #if defined( LIBVLC_USE_PTHREAD )
217     pthread_mutex_unlock( &once_mutex );
218 #endif
219 }
220
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 );
224 #endif
225
226 /*****************************************************************************
227  * vlc_mutex_init: initialize a mutex
228  *****************************************************************************/
229 int vlc_mutex_init( vlc_mutex_t *p_mutex )
230 {
231 #if defined( LIBVLC_USE_PTHREAD )
232     pthread_mutexattr_t attr;
233     int                 i_result;
234
235     pthread_mutexattr_init( &attr );
236
237 # ifndef NDEBUG
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 );
241 #  else
242     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
243 #  endif
244 # endif
245     i_result = pthread_mutex_init( p_mutex, &attr );
246     pthread_mutexattr_destroy( &attr );
247     return i_result;
248
249 #elif defined( WIN32 )
250     InitializeCriticalSection (&p_mutex->mutex);
251     p_mutex->recursive = false;
252     return 0;
253
254 #endif
255 }
256
257 /*****************************************************************************
258  * vlc_mutex_init: initialize a recursive mutex (Do not use)
259  *****************************************************************************/
260 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
261 {
262 #if defined( LIBVLC_USE_PTHREAD )
263     pthread_mutexattr_t attr;
264     int                 i_result;
265
266     pthread_mutexattr_init( &attr );
267 #  if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
268     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
269 #  else
270     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
271 #  endif
272     i_result = pthread_mutex_init( p_mutex, &attr );
273     pthread_mutexattr_destroy( &attr );
274     return( i_result );
275
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;
281     return 0;
282
283 #endif
284 }
285
286
287 /**
288  * Destroys a mutex. The mutex must not be locked.
289  *
290  * @param p_mutex mutex to destroy
291  * @return always succeeds
292  */
293 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
294 {
295 #if defined( LIBVLC_USE_PTHREAD )
296     int val = pthread_mutex_destroy( p_mutex );
297     VLC_THREAD_ASSERT ("destroying mutex");
298
299 #elif defined( WIN32 )
300     DeleteCriticalSection (&p_mutex->mutex);
301
302 #endif
303 }
304
305 /**
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.
309  *
310  * @param p_mutex mutex initialized with vlc_mutex_init() or
311  *                vlc_mutex_init_recursive()
312  */
313 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
314 {
315 #if defined(LIBVLC_USE_PTHREAD)
316     int val = pthread_mutex_lock( p_mutex );
317     VLC_THREAD_ASSERT ("locking mutex");
318
319 #elif defined( WIN32 )
320     if (p_mutex->recursive)
321     {
322         DWORD self = GetCurrentThreadId ();
323
324         if ((DWORD)InterlockedCompareExchange (&p_mutex->owner, self,
325                                                self) == self)
326         {   /* We already locked this recursive mutex */
327             p_mutex->recursion++;
328             return;
329         }
330
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 */
335         return;
336     }
337     /* Non-recursive mutex */
338     EnterCriticalSection (&p_mutex->mutex);
339
340 #endif
341 }
342
343
344 /**
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().
347  */
348 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
349 {
350 #if defined(LIBVLC_USE_PTHREAD)
351     int val = pthread_mutex_unlock( p_mutex );
352     VLC_THREAD_ASSERT ("unlocking mutex");
353
354 #elif defined( WIN32 )
355     if (p_mutex->recursive)
356     {
357         if (p_mutex->recursion != 0)
358         {
359             p_mutex->recursion--;
360             return; /* We still own this mutex */
361         }
362
363         /* We release the mutex */
364         InterlockedExchange (&p_mutex->owner, 0);
365         /* fall through */
366     }
367     LeaveCriticalSection (&p_mutex->mutex);
368
369 #endif
370 }
371
372 /*****************************************************************************
373  * vlc_cond_init: initialize a condition variable
374  *****************************************************************************/
375 int vlc_cond_init( vlc_cond_t *p_condvar )
376 {
377 #if defined( LIBVLC_USE_PTHREAD )
378     pthread_condattr_t attr;
379     int ret;
380
381     ret = pthread_condattr_init (&attr);
382     if (ret)
383         return ret;
384
385 # if !defined (_POSIX_CLOCK_SELECTION)
386    /* Fairly outdated POSIX support (that was defined in 2001) */
387 #  define _POSIX_CLOCK_SELECTION (-1)
388 # endif
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);
392 # endif
393
394     ret = pthread_cond_init (p_condvar, &attr);
395     pthread_condattr_destroy (&attr);
396     return ret;
397
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;
402
403 #endif
404 }
405
406 /**
407  * Destroys a condition variable. No threads shall be waiting or signaling the
408  * condition.
409  * @param p_condvar condition variable to destroy
410  */
411 void vlc_cond_destroy (vlc_cond_t *p_condvar)
412 {
413 #if defined( LIBVLC_USE_PTHREAD )
414     int val = pthread_cond_destroy( p_condvar );
415     VLC_THREAD_ASSERT ("destroying condition");
416
417 #elif defined( WIN32 )
418     CloseHandle( *p_condvar );
419
420 #endif
421 }
422
423 /**
424  * Wakes up one thread waiting on a condition variable, if any.
425  * @param p_condvar condition variable
426  */
427 void vlc_cond_signal (vlc_cond_t *p_condvar)
428 {
429 #if defined(LIBVLC_USE_PTHREAD)
430     int val = pthread_cond_signal( p_condvar );
431     VLC_THREAD_ASSERT ("signaling condition variable");
432
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);
440
441 #endif
442 }
443
444 /**
445  * Wakes up all threads (if any) waiting on a condition variable.
446  * @param p_cond condition variable
447  */
448 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
449 {
450 #if defined (LIBVLC_USE_PTHREAD)
451     pthread_cond_broadcast (p_condvar);
452
453 #elif defined (WIN32)
454     SetEvent (*p_condvar);
455
456 #endif
457 }
458
459 #ifdef UNDER_CE
460 # warning FIXME
461 # define WaitForMultipleObjectsEx(a,b,c) WaitForMultipleObjects(a,b)
462 #endif
463
464 /**
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.
469  *
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.
474  *
475  * In case of thread cancellation, the mutex is always locked before
476  * cancellation proceeds.
477  *
478  * The canonical way to use a condition variable to wait for event foobar is:
479  @code
480    vlc_mutex_lock (&lock);
481    mutex_cleanup_push (&lock); // release the mutex in case of cancellation
482
483    while (!foobar)
484        vlc_cond_wait (&wait, &lock);
485
486    --- foobar is now true, do something about it here --
487
488    vlc_cleanup_run (); // release the mutex
489   @endcode
490  *
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
495  *
496  * @return 0 if the condition was signaled, an error code in case of timeout.
497  */
498 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
499 {
500 #if defined(LIBVLC_USE_PTHREAD)
501     int val = pthread_cond_wait( p_condvar, p_mutex );
502     VLC_THREAD_ASSERT ("waiting on condition");
503
504 #elif defined( WIN32 )
505     DWORD result;
506
507     assert (!p_mutex->recursive);
508     do
509     {
510         vlc_testcancel ();
511         LeaveCriticalSection (&p_mutex->mutex);
512         result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
513         EnterCriticalSection (&p_mutex->mutex);
514     }
515     while (result == WAIT_IO_COMPLETION);
516
517     ResetEvent (*p_condvar);
518
519 #endif
520 }
521
522 /**
523  * Waits for a condition variable up to a certain date.
524  * This works like vlc_cond_wait(), except for the additional timeout.
525  *
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
530  *
531  * @return 0 if the condition was signaled, an error code in case of timeout.
532  */
533 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
534                         mtime_t deadline)
535 {
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) };
539
540     int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
541     if (val != ETIMEDOUT)
542         VLC_THREAD_ASSERT ("timed-waiting on condition");
543     return val;
544
545 #elif defined( WIN32 )
546     DWORD result;
547
548     assert (!p_mutex->recursive);
549     do
550     {
551         vlc_testcancel ();
552
553         mtime_t total = (deadline - mdate ())/1000;
554         if( total < 0 )
555             total = 0;
556
557         DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
558         LeaveCriticalSection (&p_mutex->mutex);
559         result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
560         EnterCriticalSection (&p_mutex->mutex);
561     }
562     while (result == WAIT_IO_COMPLETION);
563
564     ResetEvent (*p_condvar);
565
566     return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
567
568 #endif
569 }
570
571 /*****************************************************************************
572  * vlc_tls_create: create a thread-local variable
573  *****************************************************************************/
574 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
575 {
576     int i_ret;
577
578 #if defined( LIBVLC_USE_PTHREAD )
579     i_ret =  pthread_key_create( p_tls, destr );
580 #elif defined( UNDER_CE )
581     i_ret = ENOSYS;
582 #elif defined( WIN32 )
583     /* FIXME: remember/use the destr() callback and stop leaking whatever */
584     *p_tls = TlsAlloc();
585     i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
586 #else
587 # error Unimplemented!
588 #endif
589     return i_ret;
590 }
591
592 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
593 {
594 #if defined( LIBVLC_USE_PTHREAD )
595     pthread_key_delete (*p_tls);
596 #elif defined( UNDER_CE )
597 #elif defined( WIN32 )
598     TlsFree (*p_tls);
599 #else
600 # error Unimplemented!
601 #endif
602 }
603
604 #if defined (LIBVLC_USE_PTHREAD)
605 #elif defined (WIN32)
606 static unsigned __stdcall vlc_entry (void *data)
607 {
608     vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
609     vlc_thread_t self = data;
610
611     vlc_threadvar_set (&cancel_key, &cancel_data);
612     self->data = self->entry (self->data);
613     return 0;
614 }
615 #endif
616
617 /**
618  * Creates and starts new thread.
619  *
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.
625  */
626 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
627                int priority)
628 {
629     int ret;
630
631 #if defined( LIBVLC_USE_PTHREAD )
632     pthread_attr_t attr;
633     pthread_attr_init (&attr);
634
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.
639      *
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.
644      */
645     sigset_t oldset;
646     {
647         sigset_t set;
648         sigemptyset (&set);
649         sigdelset (&set, SIGHUP);
650         sigaddset (&set, SIGINT);
651         sigaddset (&set, SIGQUIT);
652         sigaddset (&set, SIGTERM);
653
654         sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
655         pthread_sigmask (SIG_BLOCK, &set, &oldset);
656     }
657     {
658         struct sched_param sp = { .sched_priority = priority, };
659         int policy;
660
661         if (sp.sched_priority <= 0)
662             sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
663         else
664             sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
665
666         pthread_attr_setschedpolicy (&attr, policy);
667         pthread_attr_setschedparam (&attr, &sp);
668     }
669
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.
675      *
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).
679      *
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)
683
684 #ifdef VLC_STACKSIZE
685     ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
686     assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
687 #endif
688
689     ret = pthread_create (p_handle, &attr, entry, data);
690     pthread_sigmask (SIG_SETMASK, &oldset, NULL);
691     pthread_attr_destroy (&attr);
692
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) */
698     HANDLE hThread;
699     vlc_thread_t th = malloc (sizeof (*th));
700
701     if (th == NULL)
702         return ENOMEM;
703
704     th->data = data;
705     th->entry = entry;
706 #if defined( UNDER_CE )
707     hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
708 #else
709     hThread = (HANDLE)(uintptr_t)
710         _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
711 #endif
712
713     if (hThread)
714     {
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))
720         {
721             CloseHandle (hThread);
722             free (th);
723             return ENOMEM;
724         }
725
726         ResumeThread (hThread);
727         if (priority)
728             SetThreadPriority (hThread, priority);
729
730         ret = 0;
731         *p_handle = th;
732     }
733     else
734     {
735         ret = errno;
736         free (th);
737     }
738
739 #endif
740     return ret;
741 }
742
743 #if defined (WIN32)
744 /* APC procedure for thread cancellation */
745 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
746 {
747     (void)dummy;
748     vlc_control_cancel (VLC_DO_CANCEL);
749 }
750 #endif
751
752 /**
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
757  * cancelled or not.
758  */
759 void vlc_cancel (vlc_thread_t thread_id)
760 {
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);
765 #else
766 #   warning vlc_cancel is not implemented!
767 #endif
768 }
769
770 /**
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_
773  * occur.
774  *
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.
778  */
779 void vlc_join (vlc_thread_t handle, void **result)
780 {
781 #if defined( LIBVLC_USE_PTHREAD )
782     int val = pthread_join (handle, result);
783     if (val)
784         vlc_thread_fatal ("joining thread", val, __func__, __FILE__, __LINE__);
785
786 #elif defined( UNDER_CE ) || defined( WIN32 )
787     do
788         vlc_testcancel ();
789     while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
790                                                         == WAIT_IO_COMPLETION);
791
792     CloseHandle (handle->handle);
793     if (result)
794         *result = handle->data;
795     free (handle);
796
797 #endif
798 }
799
800
801 struct vlc_thread_boot
802 {
803     void * (*entry) (vlc_object_t *);
804     vlc_object_t *object;
805 };
806
807 static void *thread_entry (void *data)
808 {
809     vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
810     void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
811
812     free (data);
813     msg_Dbg (obj, "thread started");
814     func (obj);
815     msg_Dbg (obj, "thread ended");
816
817     return NULL;
818 }
819
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 )
829 {
830     int i_ret;
831     vlc_object_internals_t *p_priv = vlc_internals( p_this );
832
833     struct vlc_thread_boot *boot = malloc (sizeof (*boot));
834     if (boot == NULL)
835         return errno;
836     boot->entry = func;
837     boot->object = p_this;
838
839     vlc_object_lock( p_this );
840
841     /* Make sure we don't re-create a thread if the object has already one */
842     assert( !p_priv->b_thread );
843
844 #if defined( LIBVLC_USE_PTHREAD )
845 #ifndef __APPLE__
846     if( config_GetInt( p_this, "rt-priority" ) > 0 )
847 #endif
848     {
849         /* Hack to avoid error msg */
850         if( config_GetType( p_this, "rt-offset" ) )
851             i_priority += config_GetInt( p_this, "rt-offset" );
852     }
853 #endif
854
855     i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
856     if( i_ret == 0 )
857     {
858         if( b_wait )
859         {
860             msg_Dbg( p_this, "waiting for thread initialization" );
861             vlc_object_wait( p_this );
862         }
863
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,
867                  psz_file, i_line );
868     }
869     else
870     {
871         errno = i_ret;
872         msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
873                          psz_name, psz_file, i_line );
874     }
875
876     vlc_object_unlock( p_this );
877     return i_ret;
878 }
879
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 )
886 {
887     vlc_object_internals_t *p_priv = vlc_internals( p_this );
888
889     if( !p_priv->b_thread )
890     {
891         msg_Err( p_this, "couldn't set priority of non-existent thread" );
892         return ESRCH;
893     }
894
895 #if defined( LIBVLC_USE_PTHREAD )
896 # ifndef __APPLE__
897     if( config_GetInt( p_this, "rt-priority" ) > 0 )
898 # endif
899     {
900         int i_error, i_policy;
901         struct sched_param param;
902
903         memset( &param, 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 )
907         {
908             param.sched_priority = (-1) * i_priority;
909             i_policy = SCHED_OTHER;
910         }
911         else
912         {
913             param.sched_priority = i_priority;
914             i_policy = SCHED_RR;
915         }
916         if( (i_error = pthread_setschedparam( p_priv->thread_id,
917                                               i_policy, &param )) )
918         {
919             errno = i_error;
920             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
921                       psz_file, i_line );
922             i_priority = 0;
923         }
924     }
925
926 #elif defined( WIN32 ) || defined( UNDER_CE )
927     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
928
929     if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
930     {
931         msg_Warn( p_this, "couldn't set a faster priority" );
932         return 1;
933     }
934
935 #endif
936
937     return 0;
938 }
939
940 /*****************************************************************************
941  * vlc_thread_join: wait until a thread exits, inner version
942  *****************************************************************************/
943 void __vlc_thread_join( vlc_object_t *p_this )
944 {
945     vlc_object_internals_t *p_priv = vlc_internals( p_this );
946
947 #if defined( LIBVLC_USE_PTHREAD )
948     vlc_join (p_priv->thread_id, NULL);
949
950 #elif defined( UNDER_CE ) || defined( WIN32 )
951     HANDLE hThread;
952     FILETIME create_ft, exit_ft, kernel_ft, user_ft;
953     int64_t real_time, kernel_time, user_time;
954
955     if( ! DuplicateHandle(GetCurrentProcess(),
956             p_priv->thread_id->handle,
957             GetCurrentProcess(),
958             &hThread,
959             0,
960             FALSE,
961             DUPLICATE_SAME_ACCESS) )
962     {
963         p_priv->b_thread = false;
964         return; /* We have a problem! */
965     }
966
967     vlc_join( p_priv->thread_id, NULL );
968
969     if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
970     {
971         real_time =
972           ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
973           ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
974         real_time /= 10;
975
976         kernel_time =
977           ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
978            kernel_ft.dwLowDateTime) / 10;
979
980         user_time =
981           ((((int64_t)user_ft.dwHighDateTime)<<32)|
982            user_ft.dwLowDateTime) / 10;
983
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) );
992     }
993     CloseHandle( hThread );
994
995 #else
996     vlc_join( p_priv->thread_id, NULL );
997
998 #endif
999
1000     p_priv->b_thread = false;
1001 }
1002
1003 void vlc_thread_cancel (vlc_object_t *obj)
1004 {
1005     vlc_object_internals_t *priv = vlc_internals (obj);
1006
1007     if (priv->b_thread)
1008         vlc_cancel (priv->thread_id);
1009 }
1010
1011 void vlc_control_cancel (int cmd, ...)
1012 {
1013     /* NOTE: This function only modifies thread-specific data, so there is no
1014      * need to lock anything. */
1015 #ifdef LIBVLC_USE_PTHREAD_CANCEL
1016     (void) cmd;
1017     assert (0);
1018 #else
1019     va_list ap;
1020
1021     vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
1022     if (nfo == NULL)
1023     {
1024 #ifdef WIN32
1025         /* Main thread - cannot be cancelled anyway */
1026         return;
1027 #else
1028         nfo = malloc (sizeof (*nfo));
1029         if (nfo == NULL)
1030             return; /* Uho! Expect problems! */
1031         *nfo = VLC_CANCEL_INIT;
1032         vlc_threadvar_set (&cancel_key, nfo);
1033 #endif
1034     }
1035
1036     va_start (ap, cmd);
1037     switch (cmd)
1038     {
1039         case VLC_SAVE_CANCEL:
1040         {
1041             int *p_state = va_arg (ap, int *);
1042             *p_state = nfo->killable;
1043             nfo->killable = false;
1044             break;
1045         }
1046
1047         case VLC_RESTORE_CANCEL:
1048         {
1049             int state = va_arg (ap, int);
1050             nfo->killable = state != 0;
1051             break;
1052         }
1053
1054         case VLC_TEST_CANCEL:
1055             if (nfo->killable && nfo->killed)
1056             {
1057                 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
1058                      p->proc (p->data);
1059 #ifndef WIN32
1060                 free (nfo);
1061 #endif
1062 #if defined (LIBVLC_USE_PTHREAD)
1063                 pthread_exit (PTHREAD_CANCELLED);
1064 #elif defined (WIN32)
1065                 _endthread ();
1066 #else
1067 # error Not implemented!
1068 #endif
1069             }
1070             break;
1071
1072         case VLC_DO_CANCEL:
1073             nfo->killed = true;
1074             break;
1075
1076         case VLC_CLEANUP_PUSH:
1077         {
1078             /* cleaner is a pointer to the caller stack, no need to allocate
1079              * and copy anything. As a nice side effect, this cannot fail. */
1080             vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
1081             cleaner->next = nfo->cleaners;
1082             nfo->cleaners = cleaner;
1083             break;
1084         }
1085
1086         case VLC_CLEANUP_POP:
1087         {
1088             nfo->cleaners = nfo->cleaners->next;
1089             break;
1090         }
1091     }
1092     va_end (ap);
1093 #endif
1094 }
1095
1096
1097 #undef var_AcquireMutex
1098 /**
1099  * Finds a process-wide mutex, creates it if needed, and locks it.
1100  * Unlock with vlc_mutex_unlock().
1101  * FIXME: This is very inefficient, this is not memory-safe and this leaks
1102  * memory. Use static locks instead.
1103  */
1104 vlc_mutex_t *var_AcquireMutex( const char *name )
1105 {
1106     vlc_mutex_t *lock;
1107
1108     vlc_mutex_lock (&named_mutexes.lock);
1109     lock = vlc_dictionary_value_for_key (&named_mutexes.list, name);
1110     if (lock == kVLCDictionaryNotFound)
1111     {
1112         lock = malloc (sizeof (*lock));
1113         vlc_mutex_init (lock);
1114         vlc_dictionary_insert (&named_mutexes.list, name, lock);
1115     }
1116     vlc_mutex_unlock (&named_mutexes.lock);
1117
1118     vlc_mutex_lock (lock);
1119     return lock;
1120 }