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