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