]> git.sesse.net Git - vlc/blob - src/misc/threads.c
Remove vlc_global()
[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 /**
56  * Global process-wide VLC object.
57  * Contains the global named mutexes.
58  * TODO: remove it.
59  */
60 static vlc_object_t *p_root;
61
62 #ifdef HAVE_EXECINFO_H
63 # include <execinfo.h>
64 #endif
65
66 /**
67  * Print a backtrace to the standard error for debugging purpose.
68  */
69 void vlc_trace (const char *fn, const char *file, unsigned line)
70 {
71      fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
72      fflush (stderr); /* needed before switch to low-level I/O */
73 #ifdef HAVE_BACKTRACE
74      void *stack[20];
75      int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
76      backtrace_symbols_fd (stack, len, 2);
77 #endif
78 #ifndef WIN32
79      fsync (2);
80 #endif
81 }
82
83 static inline unsigned long vlc_threadid (void)
84 {
85 #if defined(LIBVLC_USE_PTHREAD)
86      union { pthread_t th; unsigned long int i; } v = { };
87      v.th = pthread_self ();
88      return v.i;
89
90 #elif defined (WIN32)
91      return GetCurrentThreadId ();
92
93 #else
94      return 0;
95
96 #endif
97 }
98
99 /*****************************************************************************
100  * vlc_thread_fatal: Report an error from the threading layer
101  *****************************************************************************
102  * This is mostly meant for debugging.
103  *****************************************************************************/
104 static void
105 vlc_thread_fatal (const char *action, int error,
106                   const char *function, const char *file, unsigned line)
107 {
108     fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
109              action, error, vlc_threadid ());
110     vlc_trace (function, file, line);
111
112     /* Sometimes strerror_r() crashes too, so make sure we print an error
113      * message before we invoke it */
114 #ifdef __GLIBC__
115     /* Avoid the strerror_r() prototype brain damage in glibc */
116     errno = error;
117     fprintf (stderr, " Error message: %m\n");
118 #elif !defined (WIN32)
119     char buf[1000];
120     const char *msg;
121
122     switch (strerror_r (error, buf, sizeof (buf)))
123     {
124         case 0:
125             msg = buf;
126             break;
127         case ERANGE: /* should never happen */
128             msg = "unknwon (too big to display)";
129             break;
130         default:
131             msg = "unknown (invalid error number)";
132             break;
133     }
134     fprintf (stderr, " Error message: %s\n", msg);
135 #endif
136     fflush (stderr);
137
138     abort ();
139 }
140
141 #ifndef NDEBUG
142 # define VLC_THREAD_ASSERT( action ) \
143     if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
144 #else
145 # define VLC_THREAD_ASSERT( action ) ((void)val)
146 #endif
147
148 /**
149  * Per-thread cancellation data
150  */
151 #ifndef LIBVLC_USE_PTHREAD_CANCEL
152 typedef struct vlc_cancel_t
153 {
154     vlc_cleanup_t *cleaners;
155     bool           killable;
156     bool           killed;
157 } vlc_cancel_t;
158
159 # define VLC_CANCEL_INIT { NULL, true, false }
160 #endif
161
162 /*****************************************************************************
163  * vlc_threads_init: initialize threads system
164  *****************************************************************************
165  * This function requires lazy initialization of a global lock in order to
166  * keep the library really thread-safe. Some architectures don't support this
167  * and thus do not guarantee the complete reentrancy.
168  *****************************************************************************/
169 int vlc_threads_init( void )
170 {
171     int i_ret = VLC_SUCCESS;
172
173     /* If we have lazy mutex initialization, use it. Otherwise, we just
174      * hope nothing wrong happens. */
175 #if defined( LIBVLC_USE_PTHREAD )
176     pthread_mutex_lock( &once_mutex );
177 #endif
178
179     if( i_initializations == 0 )
180     {
181         p_root = vlc_custom_create( (vlc_object_t *)NULL, sizeof( *p_root ),
182                                     VLC_OBJECT_GENERIC, "root" );
183         if( p_root == NULL )
184         {
185             i_ret = VLC_ENOMEM;
186             goto out;
187         }
188
189         /* We should be safe now. Do all the initialization stuff we want. */
190 #ifndef LIBVLC_USE_PTHREAD_CANCEL
191         vlc_threadvar_create( &cancel_key, free );
192 #endif
193     }
194     i_initializations++;
195
196 out:
197     /* If we have lazy mutex initialization support, unlock the mutex.
198      * Otherwize, we are screwed. */
199 #if defined( LIBVLC_USE_PTHREAD )
200     pthread_mutex_unlock( &once_mutex );
201 #endif
202
203     return i_ret;
204 }
205
206 /*****************************************************************************
207  * vlc_threads_end: stop threads system
208  *****************************************************************************
209  * FIXME: This function is far from being threadsafe.
210  *****************************************************************************/
211 void vlc_threads_end( void )
212 {
213 #if defined( LIBVLC_USE_PTHREAD )
214     pthread_mutex_lock( &once_mutex );
215 #endif
216
217     assert( i_initializations > 0 );
218
219     if( i_initializations == 1 )
220     {
221         vlc_object_release( p_root );
222 #ifndef LIBVLC_USE_PTHREAD
223         vlc_threadvar_delete( &cancel_key );
224 #endif
225     }
226     i_initializations--;
227
228 #if defined( LIBVLC_USE_PTHREAD )
229     pthread_mutex_unlock( &once_mutex );
230 #endif
231 }
232
233 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
234 /* This is not prototyped under glibc, though it exists. */
235 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
236 #endif
237
238 /*****************************************************************************
239  * vlc_mutex_init: initialize a mutex
240  *****************************************************************************/
241 int vlc_mutex_init( vlc_mutex_t *p_mutex )
242 {
243 #if defined( LIBVLC_USE_PTHREAD )
244     pthread_mutexattr_t attr;
245     int                 i_result;
246
247     pthread_mutexattr_init( &attr );
248
249 # ifndef NDEBUG
250     /* Create error-checking mutex to detect problems more easily. */
251 #  if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
252     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
253 #  else
254     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
255 #  endif
256 # endif
257     i_result = pthread_mutex_init( p_mutex, &attr );
258     pthread_mutexattr_destroy( &attr );
259     return i_result;
260
261 #elif defined( WIN32 )
262     InitializeCriticalSection (&p_mutex->mutex);
263     p_mutex->recursive = false;
264     return 0;
265
266 #endif
267 }
268
269 /*****************************************************************************
270  * vlc_mutex_init: initialize a recursive mutex (Do not use)
271  *****************************************************************************/
272 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
273 {
274 #if defined( LIBVLC_USE_PTHREAD )
275     pthread_mutexattr_t attr;
276     int                 i_result;
277
278     pthread_mutexattr_init( &attr );
279 #  if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
280     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
281 #  else
282     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
283 #  endif
284     i_result = pthread_mutex_init( p_mutex, &attr );
285     pthread_mutexattr_destroy( &attr );
286     return( i_result );
287
288 #elif defined( WIN32 )
289     InitializeCriticalSection( &p_mutex->mutex );
290     p_mutex->owner = 0; /* the error value for GetThreadId()! */
291     p_mutex->recursion = 0;
292     p_mutex->recursive = true;
293     return 0;
294
295 #endif
296 }
297
298
299 /**
300  * Destroys a mutex. The mutex must not be locked.
301  *
302  * @param p_mutex mutex to destroy
303  * @return always succeeds
304  */
305 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
306 {
307 #if defined( LIBVLC_USE_PTHREAD )
308     int val = pthread_mutex_destroy( p_mutex );
309     VLC_THREAD_ASSERT ("destroying mutex");
310
311 #elif defined( WIN32 )
312     DeleteCriticalSection (&p_mutex->mutex);
313
314 #endif
315 }
316
317 /**
318  * Acquires a mutex. If needed, waits for any other thread to release it.
319  * Beware of deadlocks when locking multiple mutexes at the same time,
320  * or when using mutexes from callbacks.
321  *
322  * @param p_mutex mutex initialized with vlc_mutex_init() or
323  *                vlc_mutex_init_recursive()
324  */
325 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
326 {
327 #if defined(LIBVLC_USE_PTHREAD)
328     int val = pthread_mutex_lock( p_mutex );
329     VLC_THREAD_ASSERT ("locking mutex");
330
331 #elif defined( WIN32 )
332     if (p_mutex->recursive)
333     {
334         DWORD self = GetCurrentThreadId ();
335
336         if ((DWORD)InterlockedCompareExchange (&p_mutex->owner, self,
337                                                self) == self)
338         {   /* We already locked this recursive mutex */
339             p_mutex->recursion++;
340             return;
341         }
342
343         /* We need to lock this recursive mutex */
344         EnterCriticalSection (&p_mutex->mutex);
345         self = InterlockedExchange (&p_mutex->owner, self);
346         assert (self == 0); /* no previous owner */
347         return;
348     }
349     /* Non-recursive mutex */
350     EnterCriticalSection (&p_mutex->mutex);
351
352 #endif
353 }
354
355
356 /**
357  * Releases a mutex (or crashes if the mutex is not locked by the caller).
358  * @param p_mutex mutex locked with vlc_mutex_lock().
359  */
360 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
361 {
362 #if defined(LIBVLC_USE_PTHREAD)
363     int val = pthread_mutex_unlock( p_mutex );
364     VLC_THREAD_ASSERT ("unlocking mutex");
365
366 #elif defined( WIN32 )
367     if (p_mutex->recursive)
368     {
369         if (p_mutex->recursion != 0)
370         {
371             p_mutex->recursion--;
372             return; /* We still own this mutex */
373         }
374
375         /* We release the mutex */
376         InterlockedExchange (&p_mutex->owner, 0);
377         /* fall through */
378     }
379     LeaveCriticalSection (&p_mutex->mutex);
380
381 #endif
382 }
383
384 /*****************************************************************************
385  * vlc_cond_init: initialize a condition variable
386  *****************************************************************************/
387 int vlc_cond_init( vlc_cond_t *p_condvar )
388 {
389 #if defined( LIBVLC_USE_PTHREAD )
390     pthread_condattr_t attr;
391     int ret;
392
393     ret = pthread_condattr_init (&attr);
394     if (ret)
395         return ret;
396
397 # if !defined (_POSIX_CLOCK_SELECTION)
398    /* Fairly outdated POSIX support (that was defined in 2001) */
399 #  define _POSIX_CLOCK_SELECTION (-1)
400 # endif
401 # if (_POSIX_CLOCK_SELECTION >= 0)
402     /* NOTE: This must be the same clock as the one in mtime.c */
403     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
404 # endif
405
406     ret = pthread_cond_init (p_condvar, &attr);
407     pthread_condattr_destroy (&attr);
408     return ret;
409
410 #elif defined( WIN32 )
411     /* Create a manual-reset event (manual reset is needed for broadcast). */
412     *p_condvar = CreateEvent( NULL, TRUE, FALSE, NULL );
413     return *p_condvar ? 0 : ENOMEM;
414
415 #endif
416 }
417
418 /**
419  * Destroys a condition variable. No threads shall be waiting or signaling the
420  * condition.
421  * @param p_condvar condition variable to destroy
422  */
423 void vlc_cond_destroy (vlc_cond_t *p_condvar)
424 {
425 #if defined( LIBVLC_USE_PTHREAD )
426     int val = pthread_cond_destroy( p_condvar );
427     VLC_THREAD_ASSERT ("destroying condition");
428
429 #elif defined( WIN32 )
430     CloseHandle( *p_condvar );
431
432 #endif
433 }
434
435 /**
436  * Wakes up one thread waiting on a condition variable, if any.
437  * @param p_condvar condition variable
438  */
439 void vlc_cond_signal (vlc_cond_t *p_condvar)
440 {
441 #if defined(LIBVLC_USE_PTHREAD)
442     int val = pthread_cond_signal( p_condvar );
443     VLC_THREAD_ASSERT ("signaling condition variable");
444
445 #elif defined( WIN32 )
446     /* NOTE: This will cause a broadcast, that is wrong.
447      * This will also wake up the next waiting thread if no thread are yet
448      * waiting, which is also wrong. However both of these issues are allowed
449      * by the provision for spurious wakeups. Better have too many wakeups
450      * than too few (= deadlocks). */
451     SetEvent (*p_condvar);
452
453 #endif
454 }
455
456 /**
457  * Wakes up all threads (if any) waiting on a condition variable.
458  * @param p_cond condition variable
459  */
460 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
461 {
462 #if defined (LIBVLC_USE_PTHREAD)
463     pthread_cond_broadcast (p_condvar);
464
465 #elif defined (WIN32)
466     SetEvent (*p_condvar);
467
468 #endif
469 }
470
471 #ifdef UNDER_CE
472 # warning FIXME
473 # define WaitForMultipleObjectsEx(a,b,c) WaitForMultipleObjects(a,b)
474 #endif
475
476 /**
477  * Waits for a condition variable. The calling thread will be suspended until
478  * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
479  * condition variable, the thread is cancelled with vlc_cancel(), or the
480  * system causes a "spurious" unsolicited wake-up.
481  *
482  * A mutex is needed to wait on a condition variable. It must <b>not</b> be
483  * a recursive mutex. Although it is possible to use the same mutex for
484  * multiple condition, it is not valid to use different mutexes for the same
485  * condition variable at the same time from different threads.
486  *
487  * In case of thread cancellation, the mutex is always locked before
488  * cancellation proceeds.
489  *
490  * The canonical way to use a condition variable to wait for event foobar is:
491  @code
492    vlc_mutex_lock (&lock);
493    mutex_cleanup_push (&lock); // release the mutex in case of cancellation
494
495    while (!foobar)
496        vlc_cond_wait (&wait, &lock);
497
498    --- foobar is now true, do something about it here --
499
500    vlc_cleanup_run (); // release the mutex
501   @endcode
502  *
503  * @param p_condvar condition variable to wait on
504  * @param p_mutex mutex which is unlocked while waiting,
505  *                then locked again when waking up.
506  * @param deadline <b>absolute</b> timeout
507  *
508  * @return 0 if the condition was signaled, an error code in case of timeout.
509  */
510 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
511 {
512 #if defined(LIBVLC_USE_PTHREAD)
513     int val = pthread_cond_wait( p_condvar, p_mutex );
514     VLC_THREAD_ASSERT ("waiting on condition");
515
516 #elif defined( WIN32 )
517     DWORD result;
518
519     assert (!p_mutex->recursive);
520     do
521     {
522         vlc_testcancel ();
523         LeaveCriticalSection (&p_mutex->mutex);
524         result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
525         EnterCriticalSection (&p_mutex->mutex);
526     }
527     while (result == WAIT_IO_COMPLETION);
528
529     ResetEvent (*p_condvar);
530
531 #endif
532 }
533
534 /**
535  * Waits for a condition variable up to a certain date.
536  * This works like vlc_cond_wait(), except for the additional timeout.
537  *
538  * @param p_condvar condition variable to wait on
539  * @param p_mutex mutex which is unlocked while waiting,
540  *                then locked again when waking up.
541  * @param deadline <b>absolute</b> timeout
542  *
543  * @return 0 if the condition was signaled, an error code in case of timeout.
544  */
545 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
546                         mtime_t deadline)
547 {
548 #if defined(LIBVLC_USE_PTHREAD)
549     lldiv_t d = lldiv( deadline, CLOCK_FREQ );
550     struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
551
552     int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
553     if (val != ETIMEDOUT)
554         VLC_THREAD_ASSERT ("timed-waiting on condition");
555     return val;
556
557 #elif defined( WIN32 )
558     DWORD result;
559
560     assert (!p_mutex->recursive);
561     do
562     {
563         vlc_testcancel ();
564
565         mtime_t total = (deadline - mdate ())/1000;
566         if( total < 0 )
567             total = 0;
568
569         DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
570         LeaveCriticalSection (&p_mutex->mutex);
571         result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
572         EnterCriticalSection (&p_mutex->mutex);
573     }
574     while (result == WAIT_IO_COMPLETION);
575
576     ResetEvent (*p_condvar);
577
578     return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
579
580 #endif
581 }
582
583 /*****************************************************************************
584  * vlc_tls_create: create a thread-local variable
585  *****************************************************************************/
586 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
587 {
588     int i_ret;
589
590 #if defined( LIBVLC_USE_PTHREAD )
591     i_ret =  pthread_key_create( p_tls, destr );
592 #elif defined( UNDER_CE )
593     i_ret = ENOSYS;
594 #elif defined( WIN32 )
595     /* FIXME: remember/use the destr() callback and stop leaking whatever */
596     *p_tls = TlsAlloc();
597     i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
598 #else
599 # error Unimplemented!
600 #endif
601     return i_ret;
602 }
603
604 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
605 {
606 #if defined( LIBVLC_USE_PTHREAD )
607     pthread_key_delete (*p_tls);
608 #elif defined( UNDER_CE )
609 #elif defined( WIN32 )
610     TlsFree (*p_tls);
611 #else
612 # error Unimplemented!
613 #endif
614 }
615
616 #if defined (LIBVLC_USE_PTHREAD)
617 #elif defined (WIN32)
618 static unsigned __stdcall vlc_entry (void *data)
619 {
620     vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
621     vlc_thread_t self = data;
622
623     vlc_threadvar_set (&cancel_key, &cancel_data);
624     self->data = self->entry (self->data);
625     return 0;
626 }
627 #endif
628
629 /**
630  * Creates and starts new thread.
631  *
632  * @param p_handle [OUT] pointer to write the handle of the created thread to
633  * @param entry entry point for the thread
634  * @param data data parameter given to the entry point
635  * @param priority thread priority value
636  * @return 0 on success, a standard error code on error.
637  */
638 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
639                int priority)
640 {
641     int ret;
642
643 #if defined( LIBVLC_USE_PTHREAD )
644     pthread_attr_t attr;
645     pthread_attr_init (&attr);
646
647     /* Block the signals that signals interface plugin handles.
648      * If the LibVLC caller wants to handle some signals by itself, it should
649      * block these before whenever invoking LibVLC. And it must obviously not
650      * start the VLC signals interface plugin.
651      *
652      * LibVLC will normally ignore any interruption caused by an asynchronous
653      * signal during a system call. But there may well be some buggy cases
654      * where it fails to handle EINTR (bug reports welcome). Some underlying
655      * libraries might also not handle EINTR properly.
656      */
657     sigset_t oldset;
658     {
659         sigset_t set;
660         sigemptyset (&set);
661         sigdelset (&set, SIGHUP);
662         sigaddset (&set, SIGINT);
663         sigaddset (&set, SIGQUIT);
664         sigaddset (&set, SIGTERM);
665
666         sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
667         pthread_sigmask (SIG_BLOCK, &set, &oldset);
668     }
669     {
670         struct sched_param sp = { .sched_priority = priority, };
671         int policy;
672
673         if (sp.sched_priority <= 0)
674             sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
675         else
676             sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
677
678         pthread_attr_setschedpolicy (&attr, policy);
679         pthread_attr_setschedparam (&attr, &sp);
680     }
681
682     /* The thread stack size.
683      * The lower the value, the less address space per thread, the highest
684      * maximum simultaneous threads per process. Too low values will cause
685      * stack overflows and weird crashes. Set with caution. Also keep in mind
686      * that 64-bits platforms consume more stack than 32-bits one.
687      *
688      * Thanks to on-demand paging, thread stack size only affects address space
689      * consumption. In terms of memory, threads only use what they need
690      * (rounded up to the page boundary).
691      *
692      * For example, on Linux i386, the default is 2 mega-bytes, which supports
693      * about 320 threads per processes. */
694 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
695
696 #ifdef VLC_STACKSIZE
697     ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
698     assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
699 #endif
700
701     ret = pthread_create (p_handle, &attr, entry, data);
702     pthread_sigmask (SIG_SETMASK, &oldset, NULL);
703     pthread_attr_destroy (&attr);
704
705 #elif defined( WIN32 ) || defined( UNDER_CE )
706     /* When using the MSVCRT C library you have to use the _beginthreadex
707      * function instead of CreateThread, otherwise you'll end up with
708      * memory leaks and the signal functions not working (see Microsoft
709      * Knowledge Base, article 104641) */
710     HANDLE hThread;
711     vlc_thread_t th = malloc (sizeof (*th));
712
713     if (th == NULL)
714         return ENOMEM;
715
716     th->data = data;
717     th->entry = entry;
718 #if defined( UNDER_CE )
719     hThread = CreateThread (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
720 #else
721     hThread = (HANDLE)(uintptr_t)
722         _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
723 #endif
724
725     if (hThread)
726     {
727         /* Thread closes the handle when exiting, duplicate it here
728          * to be on the safe side when joining. */
729         if (!DuplicateHandle (GetCurrentProcess (), hThread,
730                               GetCurrentProcess (), &th->handle, 0, FALSE,
731                               DUPLICATE_SAME_ACCESS))
732         {
733             CloseHandle (hThread);
734             free (th);
735             return ENOMEM;
736         }
737
738         ResumeThread (hThread);
739         if (priority)
740             SetThreadPriority (hThread, priority);
741
742         ret = 0;
743         *p_handle = th;
744     }
745     else
746     {
747         ret = errno;
748         free (th);
749     }
750
751 #endif
752     return ret;
753 }
754
755 #if defined (WIN32)
756 /* APC procedure for thread cancellation */
757 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
758 {
759     (void)dummy;
760     vlc_control_cancel (VLC_DO_CANCEL);
761 }
762 #endif
763
764 /**
765  * Marks a thread as cancelled. Next time the target thread reaches a
766  * cancellation point (while not having disabled cancellation), it will
767  * run its cancellation cleanup handler, the thread variable destructors, and
768  * terminate. vlc_join() must be used afterward regardless of a thread being
769  * cancelled or not.
770  */
771 void vlc_cancel (vlc_thread_t thread_id)
772 {
773 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
774     pthread_cancel (thread_id);
775 #elif defined (WIN32)
776     QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
777 #else
778 #   warning vlc_cancel is not implemented!
779 #endif
780 }
781
782 /**
783  * Waits for a thread to complete (if needed), and destroys it.
784  * This is a cancellation point; in case of cancellation, the join does _not_
785  * occur.
786  *
787  * @param handle thread handle
788  * @param p_result [OUT] pointer to write the thread return value or NULL
789  * @return 0 on success, a standard error code otherwise.
790  */
791 void vlc_join (vlc_thread_t handle, void **result)
792 {
793 #if defined( LIBVLC_USE_PTHREAD )
794     int val = pthread_join (handle, result);
795     if (val)
796         vlc_thread_fatal ("joining thread", val, __func__, __FILE__, __LINE__);
797
798 #elif defined( UNDER_CE ) || defined( WIN32 )
799     do
800         vlc_testcancel ();
801     while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
802                                                         == WAIT_IO_COMPLETION);
803
804     CloseHandle (handle->handle);
805     if (result)
806         *result = handle->data;
807     free (handle);
808
809 #endif
810 }
811
812
813 struct vlc_thread_boot
814 {
815     void * (*entry) (vlc_object_t *);
816     vlc_object_t *object;
817 };
818
819 static void *thread_entry (void *data)
820 {
821     vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
822     void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
823
824     free (data);
825     msg_Dbg (obj, "thread started");
826     func (obj);
827     msg_Dbg (obj, "thread ended");
828
829     return NULL;
830 }
831
832 /*****************************************************************************
833  * vlc_thread_create: create a thread, inner version
834  *****************************************************************************
835  * Note that i_priority is only taken into account on platforms supporting
836  * userland real-time priority threads.
837  *****************************************************************************/
838 int __vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
839                          const char *psz_name, void * ( *func ) ( vlc_object_t * ),
840                          int i_priority, bool b_wait )
841 {
842     int i_ret;
843     vlc_object_internals_t *p_priv = vlc_internals( p_this );
844
845     struct vlc_thread_boot *boot = malloc (sizeof (*boot));
846     if (boot == NULL)
847         return errno;
848     boot->entry = func;
849     boot->object = p_this;
850
851     vlc_object_lock( p_this );
852
853     /* Make sure we don't re-create a thread if the object has already one */
854     assert( !p_priv->b_thread );
855
856 #if defined( LIBVLC_USE_PTHREAD )
857 #ifndef __APPLE__
858     if( config_GetInt( p_this, "rt-priority" ) > 0 )
859 #endif
860     {
861         /* Hack to avoid error msg */
862         if( config_GetType( p_this, "rt-offset" ) )
863             i_priority += config_GetInt( p_this, "rt-offset" );
864     }
865 #endif
866
867     i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
868     if( i_ret == 0 )
869     {
870         if( b_wait )
871         {
872             msg_Dbg( p_this, "waiting for thread initialization" );
873             vlc_object_wait( p_this );
874         }
875
876         p_priv->b_thread = true;
877         msg_Dbg( p_this, "thread %lu (%s) created at priority %d (%s:%d)",
878                  (unsigned long)p_priv->thread_id, psz_name, i_priority,
879                  psz_file, i_line );
880     }
881     else
882     {
883         errno = i_ret;
884         msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
885                          psz_name, psz_file, i_line );
886     }
887
888     vlc_object_unlock( p_this );
889     return i_ret;
890 }
891
892 /*****************************************************************************
893  * vlc_thread_set_priority: set the priority of the current thread when we
894  * couldn't set it in vlc_thread_create (for instance for the main thread)
895  *****************************************************************************/
896 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
897                                int i_line, int i_priority )
898 {
899     vlc_object_internals_t *p_priv = vlc_internals( p_this );
900
901     if( !p_priv->b_thread )
902     {
903         msg_Err( p_this, "couldn't set priority of non-existent thread" );
904         return ESRCH;
905     }
906
907 #if defined( LIBVLC_USE_PTHREAD )
908 # ifndef __APPLE__
909     if( config_GetInt( p_this, "rt-priority" ) > 0 )
910 # endif
911     {
912         int i_error, i_policy;
913         struct sched_param param;
914
915         memset( &param, 0, sizeof(struct sched_param) );
916         if( config_GetType( p_this, "rt-offset" ) )
917             i_priority += config_GetInt( p_this, "rt-offset" );
918         if( i_priority <= 0 )
919         {
920             param.sched_priority = (-1) * i_priority;
921             i_policy = SCHED_OTHER;
922         }
923         else
924         {
925             param.sched_priority = i_priority;
926             i_policy = SCHED_RR;
927         }
928         if( (i_error = pthread_setschedparam( p_priv->thread_id,
929                                               i_policy, &param )) )
930         {
931             errno = i_error;
932             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
933                       psz_file, i_line );
934             i_priority = 0;
935         }
936     }
937
938 #elif defined( WIN32 ) || defined( UNDER_CE )
939     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
940
941     if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
942     {
943         msg_Warn( p_this, "couldn't set a faster priority" );
944         return 1;
945     }
946
947 #endif
948
949     return 0;
950 }
951
952 /*****************************************************************************
953  * vlc_thread_join: wait until a thread exits, inner version
954  *****************************************************************************/
955 void __vlc_thread_join( vlc_object_t *p_this )
956 {
957     vlc_object_internals_t *p_priv = vlc_internals( p_this );
958
959 #if defined( LIBVLC_USE_PTHREAD )
960     vlc_join (p_priv->thread_id, NULL);
961
962 #elif defined( UNDER_CE ) || defined( WIN32 )
963     HANDLE hThread;
964     FILETIME create_ft, exit_ft, kernel_ft, user_ft;
965     int64_t real_time, kernel_time, user_time;
966
967     if( ! DuplicateHandle(GetCurrentProcess(),
968             p_priv->thread_id->handle,
969             GetCurrentProcess(),
970             &hThread,
971             0,
972             FALSE,
973             DUPLICATE_SAME_ACCESS) )
974     {
975         p_priv->b_thread = false;
976         return; /* We have a problem! */
977     }
978
979     vlc_join( p_priv->thread_id, NULL );
980
981     if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
982     {
983         real_time =
984           ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
985           ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
986         real_time /= 10;
987
988         kernel_time =
989           ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
990            kernel_ft.dwLowDateTime) / 10;
991
992         user_time =
993           ((((int64_t)user_ft.dwHighDateTime)<<32)|
994            user_ft.dwLowDateTime) / 10;
995
996         msg_Dbg( p_this, "thread times: "
997                  "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
998                  real_time/60/1000000,
999                  (double)((real_time%(60*1000000))/1000000.0),
1000                  kernel_time/60/1000000,
1001                  (double)((kernel_time%(60*1000000))/1000000.0),
1002                  user_time/60/1000000,
1003                  (double)((user_time%(60*1000000))/1000000.0) );
1004     }
1005     CloseHandle( hThread );
1006
1007 #else
1008     vlc_join( p_priv->thread_id, NULL );
1009
1010 #endif
1011
1012     p_priv->b_thread = false;
1013 }
1014
1015 void vlc_thread_cancel (vlc_object_t *obj)
1016 {
1017     vlc_object_internals_t *priv = vlc_internals (obj);
1018
1019     if (priv->b_thread)
1020         vlc_cancel (priv->thread_id);
1021 }
1022
1023 void vlc_control_cancel (int cmd, ...)
1024 {
1025     /* NOTE: This function only modifies thread-specific data, so there is no
1026      * need to lock anything. */
1027 #ifdef LIBVLC_USE_PTHREAD_CANCEL
1028     (void) cmd;
1029     assert (0);
1030 #else
1031     va_list ap;
1032
1033     vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
1034     if (nfo == NULL)
1035     {
1036 #ifdef WIN32
1037         /* Main thread - cannot be cancelled anyway */
1038         return;
1039 #else
1040         nfo = malloc (sizeof (*nfo));
1041         if (nfo == NULL)
1042             return; /* Uho! Expect problems! */
1043         *nfo = VLC_CANCEL_INIT;
1044         vlc_threadvar_set (&cancel_key, nfo);
1045 #endif
1046     }
1047
1048     va_start (ap, cmd);
1049     switch (cmd)
1050     {
1051         case VLC_SAVE_CANCEL:
1052         {
1053             int *p_state = va_arg (ap, int *);
1054             *p_state = nfo->killable;
1055             nfo->killable = false;
1056             break;
1057         }
1058
1059         case VLC_RESTORE_CANCEL:
1060         {
1061             int state = va_arg (ap, int);
1062             nfo->killable = state != 0;
1063             break;
1064         }
1065
1066         case VLC_TEST_CANCEL:
1067             if (nfo->killable && nfo->killed)
1068             {
1069                 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
1070                      p->proc (p->data);
1071 #ifndef WIN32
1072                 free (nfo);
1073 #endif
1074 #if defined (LIBVLC_USE_PTHREAD)
1075                 pthread_exit (PTHREAD_CANCELLED);
1076 #elif defined (WIN32)
1077                 _endthread ();
1078 #else
1079 # error Not implemented!
1080 #endif
1081             }
1082             break;
1083
1084         case VLC_DO_CANCEL:
1085             nfo->killed = true;
1086             break;
1087
1088         case VLC_CLEANUP_PUSH:
1089         {
1090             /* cleaner is a pointer to the caller stack, no need to allocate
1091              * and copy anything. As a nice side effect, this cannot fail. */
1092             vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
1093             cleaner->next = nfo->cleaners;
1094             nfo->cleaners = cleaner;
1095             break;
1096         }
1097
1098         case VLC_CLEANUP_POP:
1099         {
1100             nfo->cleaners = nfo->cleaners->next;
1101             break;
1102         }
1103     }
1104     va_end (ap);
1105 #endif
1106 }
1107
1108
1109 #undef var_AcquireMutex
1110 /**
1111  * Finds a process-wide mutex, creates it if needed, and locks it.
1112  * Unlock with vlc_mutex_unlock().
1113  */
1114 vlc_mutex_t *var_AcquireMutex( const char *name )
1115 {
1116     vlc_value_t val;
1117
1118     if( var_Create( p_root, name, VLC_VAR_MUTEX ) )
1119         return NULL;
1120
1121     var_Get( p_root, name, &val );
1122     vlc_mutex_lock( val.p_address );
1123     return val.p_address;
1124 }