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