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