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