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