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