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