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