1 /*****************************************************************************
2 * thread.c : Win32 back-end for LibVLC
3 *****************************************************************************
4 * Copyright (C) 1999-2009 the VideoLAN team
6 * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
7 * Samuel Hocevar <sam@zoy.org>
8 * Gildas Bazin <gbazin@netcourrier.com>
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.
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.
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 *****************************************************************************/
32 #include <vlc_common.h>
40 # include <mmsystem.h>
43 static vlc_threadvar_t cancel_key;
46 * Per-thread cancellation data
48 typedef struct vlc_cancel_t
50 vlc_cleanup_t *cleaners;
59 # define VLC_CANCEL_INIT { NULL, true, false }
61 # define VLC_CANCEL_INIT { NULL, NULL, true, false }
65 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy);
67 static DWORD vlc_cancelable_wait (DWORD count, const HANDLE *handles,
70 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
73 /* Main thread - cannot be cancelled anyway */
74 return WaitForMultipleObjects (count, handles, FALSE, delay);
76 HANDLE new_handles[count + 1];
77 memcpy(new_handles, handles, count * sizeof(HANDLE));
78 new_handles[count] = nfo->cancel_event;
79 DWORD result = WaitForMultipleObjects (count + 1, new_handles, FALSE,
81 if (result == WAIT_OBJECT_0 + count)
83 vlc_cancel_self (NULL);
84 return WAIT_IO_COMPLETION;
92 DWORD SleepEx (DWORD dwMilliseconds, BOOL bAlertable)
96 DWORD result = vlc_cancelable_wait (0, NULL, dwMilliseconds);
97 return (result == WAIT_TIMEOUT) ? 0 : WAIT_IO_COMPLETION;
101 Sleep(dwMilliseconds);
106 DWORD WaitForSingleObjectEx (HANDLE hHandle, DWORD dwMilliseconds,
111 /* The MSDN documentation specifies different return codes,
112 * but in practice they are the same. We just check that it
114 #if WAIT_ABANDONED != WAIT_ABANDONED_0
115 # error Windows headers changed, code needs to be rewritten!
117 return vlc_cancelable_wait (1, &hHandle, dwMilliseconds);
121 return WaitForSingleObject (hHandle, dwMilliseconds);
125 DWORD WaitForMultipleObjectsEx (DWORD nCount, const HANDLE *lpHandles,
126 BOOL bWaitAll, DWORD dwMilliseconds,
131 /* We do not support the bWaitAll case */
133 return vlc_cancelable_wait (nCount, lpHandles, dwMilliseconds);
137 return WaitForMultipleObjects (nCount, lpHandles, bWaitAll,
143 vlc_mutex_t super_mutex;
144 vlc_cond_t super_variable;
146 BOOL WINAPI DllMain (HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvReserved)
153 case DLL_PROCESS_ATTACH:
154 vlc_mutex_init (&super_mutex);
155 vlc_cond_init (&super_variable);
156 vlc_threadvar_create (&cancel_key, free);
159 case DLL_PROCESS_DETACH:
160 vlc_threadvar_delete( &cancel_key );
161 vlc_cond_destroy (&super_variable);
162 vlc_mutex_destroy (&super_mutex);
169 void vlc_mutex_init( vlc_mutex_t *p_mutex )
171 /* This creates a recursive mutex. This is OK as fast mutexes have
172 * no defined behavior in case of recursive locking. */
173 InitializeCriticalSection (&p_mutex->mutex);
174 p_mutex->dynamic = true;
177 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
179 InitializeCriticalSection( &p_mutex->mutex );
180 p_mutex->dynamic = true;
184 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
186 assert (p_mutex->dynamic);
187 DeleteCriticalSection (&p_mutex->mutex);
190 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
192 if (!p_mutex->dynamic)
193 { /* static mutexes */
194 int canc = vlc_savecancel ();
195 assert (p_mutex != &super_mutex); /* this one cannot be static */
197 vlc_mutex_lock (&super_mutex);
198 while (p_mutex->locked)
200 p_mutex->contention++;
201 vlc_cond_wait (&super_variable, &super_mutex);
202 p_mutex->contention--;
204 p_mutex->locked = true;
205 vlc_mutex_unlock (&super_mutex);
206 vlc_restorecancel (canc);
210 EnterCriticalSection (&p_mutex->mutex);
213 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
215 if (!p_mutex->dynamic)
216 { /* static mutexes */
219 assert (p_mutex != &super_mutex); /* this one cannot be static */
220 vlc_mutex_lock (&super_mutex);
221 if (!p_mutex->locked)
223 p_mutex->locked = true;
226 vlc_mutex_unlock (&super_mutex);
230 return TryEnterCriticalSection (&p_mutex->mutex) ? 0 : EBUSY;
233 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
235 if (!p_mutex->dynamic)
236 { /* static mutexes */
237 assert (p_mutex != &super_mutex); /* this one cannot be static */
239 vlc_mutex_lock (&super_mutex);
240 assert (p_mutex->locked);
241 p_mutex->locked = false;
242 if (p_mutex->contention)
243 vlc_cond_broadcast (&super_variable);
244 vlc_mutex_unlock (&super_mutex);
248 LeaveCriticalSection (&p_mutex->mutex);
251 /*** Condition variables ***/
258 static void vlc_cond_init_common (vlc_cond_t *p_condvar, unsigned clock)
260 /* Create a manual-reset event (manual reset is needed for broadcast). */
261 p_condvar->handle = CreateEvent (NULL, TRUE, FALSE, NULL);
262 if (!p_condvar->handle)
264 p_condvar->clock = clock;
267 void vlc_cond_init (vlc_cond_t *p_condvar)
269 vlc_cond_init_common (p_condvar, CLOCK_MONOTONIC);
272 void vlc_cond_init_daytime (vlc_cond_t *p_condvar)
274 vlc_cond_init_common (p_condvar, CLOCK_REALTIME);
277 void vlc_cond_destroy (vlc_cond_t *p_condvar)
279 CloseHandle (p_condvar->handle);
282 void vlc_cond_signal (vlc_cond_t *p_condvar)
284 /* NOTE: This will cause a broadcast, that is wrong.
285 * This will also wake up the next waiting thread if no threads are yet
286 * waiting, which is also wrong. However both of these issues are allowed
287 * by the provision for spurious wakeups. Better have too many wakeups
288 * than too few (= deadlocks). */
289 SetEvent (p_condvar->handle);
292 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
294 SetEvent (p_condvar->handle);
297 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
301 assert (p_mutex->dynamic); /* TODO */
305 LeaveCriticalSection (&p_mutex->mutex);
306 result = WaitForSingleObjectEx (p_condvar->handle, INFINITE, TRUE);
307 EnterCriticalSection (&p_mutex->mutex);
309 while (result == WAIT_IO_COMPLETION);
311 assert (result != WAIT_ABANDONED); /* another thread failed to cleanup! */
312 assert (result != WAIT_FAILED);
313 ResetEvent (p_condvar->handle);
316 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
321 assert (p_mutex->dynamic); /* TODO */
327 switch (p_condvar->clock)
329 case CLOCK_MONOTONIC:
332 case CLOCK_REALTIME: /* FIXME? sub-second precision */
333 total = CLOCK_FREQ * time (NULL);
338 total = (deadline - total) / 1000;
342 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
343 LeaveCriticalSection (&p_mutex->mutex);
344 result = WaitForSingleObjectEx (p_condvar->handle, delay, TRUE);
345 EnterCriticalSection (&p_mutex->mutex);
347 while (result == WAIT_IO_COMPLETION);
349 assert (result != WAIT_ABANDONED);
350 assert (result != WAIT_FAILED);
351 ResetEvent (p_condvar->handle);
353 return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
357 void vlc_sem_init (vlc_sem_t *sem, unsigned value)
359 *sem = CreateSemaphore (NULL, value, 0x7fffffff, NULL);
364 void vlc_sem_destroy (vlc_sem_t *sem)
369 int vlc_sem_post (vlc_sem_t *sem)
371 ReleaseSemaphore (*sem, 1, NULL);
372 return 0; /* FIXME */
375 void vlc_sem_wait (vlc_sem_t *sem)
382 result = WaitForSingleObjectEx (*sem, INFINITE, TRUE);
384 while (result == WAIT_IO_COMPLETION);
387 /*** Read/write locks */
388 /* SRW (Slim Read Write) locks are available in Vista+ only */
389 void vlc_rwlock_init (vlc_rwlock_t *lock)
391 vlc_mutex_init (&lock->mutex);
392 vlc_cond_init (&lock->read_wait);
393 vlc_cond_init (&lock->write_wait);
394 lock->readers = 0; /* active readers */
395 lock->writers = 0; /* waiting or active writers */
396 lock->writer = 0; /* ID of active writer */
400 * Destroys an initialized unused read/write lock.
402 void vlc_rwlock_destroy (vlc_rwlock_t *lock)
404 vlc_cond_destroy (&lock->read_wait);
405 vlc_cond_destroy (&lock->write_wait);
406 vlc_mutex_destroy (&lock->mutex);
410 * Acquires a read/write lock for reading. Recursion is allowed.
412 void vlc_rwlock_rdlock (vlc_rwlock_t *lock)
414 vlc_mutex_lock (&lock->mutex);
415 while (lock->writer != 0)
416 vlc_cond_wait (&lock->read_wait, &lock->mutex);
417 if (lock->readers == ULONG_MAX)
420 vlc_mutex_unlock (&lock->mutex);
424 * Acquires a read/write lock for writing. Recursion is not allowed.
426 void vlc_rwlock_wrlock (vlc_rwlock_t *lock)
428 vlc_mutex_lock (&lock->mutex);
429 if (lock->writers == ULONG_MAX)
432 while ((lock->readers > 0) || (lock->writer != 0))
433 vlc_cond_wait (&lock->write_wait, &lock->mutex);
435 lock->writer = GetCurrentThreadId ();
436 vlc_mutex_unlock (&lock->mutex);
440 * Releases a read/write lock.
442 void vlc_rwlock_unlock (vlc_rwlock_t *lock)
444 vlc_mutex_lock (&lock->mutex);
445 if (lock->readers > 0)
446 lock->readers--; /* Read unlock */
448 lock->writer = 0; /* Write unlock */
450 if (lock->writers > 0)
452 if (lock->readers == 0)
453 vlc_cond_signal (&lock->write_wait);
456 vlc_cond_broadcast (&lock->read_wait);
457 vlc_mutex_unlock (&lock->mutex);
460 /*** Thread-specific variables (TLS) ***/
461 int vlc_threadvar_create (vlc_threadvar_t *p_tls, void (*destr) (void *))
463 #warning FIXME: use destr() callback and stop leaking!
467 return (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
470 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
476 * Sets a thread-local variable.
477 * @param key thread-local variable key (created with vlc_threadvar_create())
478 * @param value new value for the variable for the calling thread
479 * @return 0 on success, a system error code otherwise.
481 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
483 return TlsSetValue (key, value) ? ENOMEM : 0;
487 * Gets the value of a thread-local variable for the calling thread.
488 * This function cannot fail.
489 * @return the value associated with the given variable for the calling
490 * or NULL if there is no value.
492 void *vlc_threadvar_get (vlc_threadvar_t key)
494 return TlsGetValue (key);
499 void vlc_threads_setup (libvlc_int_t *p_libvlc)
504 struct vlc_entry_data
506 void * (*func) (void *);
514 static unsigned __stdcall vlc_entry (void *p)
516 struct vlc_entry_data *entry = p;
517 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
518 void *(*func) (void *) = entry->func;
519 void *data = entry->data;
522 cancel_data.cancel_event = entry->cancel_event;
524 vlc_threadvar_set (cancel_key, &cancel_data);
525 vlc_sem_post (&entry->ready);
530 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
536 struct vlc_entry_data *entry_data = malloc (sizeof (*entry_data));
537 if (entry_data == NULL)
539 entry_data->func = entry;
540 entry_data->data = data;
541 vlc_sem_init (&entry_data->ready, 0);
544 /* When using the MSVCRT C library you have to use the _beginthreadex
545 * function instead of CreateThread, otherwise you'll end up with
546 * memory leaks and the signal functions not working (see Microsoft
547 * Knowledge Base, article 104641) */
548 hThread = (HANDLE)(uintptr_t)
549 _beginthreadex (NULL, 0, vlc_entry, entry_data, CREATE_SUSPENDED, NULL);
559 vlc_thread_t th = malloc (sizeof (*th));
562 th->cancel_event = CreateEvent (NULL, FALSE, FALSE, NULL);
563 if (th->cancel_event == NULL)
568 entry_data->cancel_event = th->cancel_event;
570 /* Not sure if CREATE_SUSPENDED + ResumeThread() is any useful on WinCE.
571 * Thread handles act up, too. */
572 th->handle = CreateThread (NULL, 128*1024, vlc_entry, entry_data,
573 CREATE_SUSPENDED, NULL);
574 if (th->handle == NULL)
576 CloseHandle (th->cancel_event);
582 hThread = th->handle;
586 ResumeThread (hThread);
588 SetThreadPriority (hThread, priority);
590 /* Prevent cancellation until cancel_data is initialized. */
591 /* XXX: This could be postponed to vlc_cancel() or avoided completely by
592 * passing the "right" pointer to vlc_cancel_self(). */
593 vlc_sem_wait (&entry_data->ready);
594 vlc_sem_destroy (&entry_data->ready);
600 vlc_sem_destroy (&entry_data->ready);
605 void vlc_join (vlc_thread_t handle, void **result)
608 # define handle handle->handle
612 while (WaitForSingleObjectEx (handle, INFINITE, TRUE)
613 == WAIT_IO_COMPLETION);
615 CloseHandle (handle);
616 assert (result == NULL); /* <- FIXME if ever needed */
619 CloseHandle (handle->cancel_event);
624 void vlc_detach (vlc_thread_t handle)
627 CloseHandle (handle);
629 /* FIXME: handle->cancel_event leak */
630 CloseHandle (handle->handle);
635 /*** Thread cancellation ***/
637 /* APC procedure for thread cancellation */
638 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
640 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
642 if (likely(nfo != NULL))
648 void vlc_cancel (vlc_thread_t thread_id)
651 QueueUserAPC (vlc_cancel_self, thread_id, 0);
653 SetEvent (thread_id->cancel_event);
657 int vlc_savecancel (void)
661 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
663 return false; /* Main thread - cannot be cancelled anyway */
665 state = nfo->killable;
666 nfo->killable = false;
670 void vlc_restorecancel (int state)
672 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
673 assert (state == false || state == true);
676 return; /* Main thread - cannot be cancelled anyway */
678 assert (!nfo->killable);
679 nfo->killable = state != 0;
682 void vlc_testcancel (void)
684 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
686 return; /* Main thread - cannot be cancelled anyway */
688 if (nfo->killable && nfo->killed)
690 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
700 void vlc_control_cancel (int cmd, ...)
702 /* NOTE: This function only modifies thread-specific data, so there is no
703 * need to lock anything. */
706 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
708 return; /* Main thread - cannot be cancelled anyway */
713 case VLC_CLEANUP_PUSH:
715 /* cleaner is a pointer to the caller stack, no need to allocate
716 * and copy anything. As a nice side effect, this cannot fail. */
717 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
718 cleaner->next = nfo->cleaners;
719 nfo->cleaners = cleaner;
723 case VLC_CLEANUP_POP:
725 nfo->cleaners = nfo->cleaners->next;
742 void (*func) (void *);
747 static void CALLBACK vlc_timer_do (void *val, BOOLEAN timeout)
749 struct vlc_timer *timer = val;
752 timer->func (timer->data);
755 static void CALLBACK vlc_timer_do (unsigned timer_id, unsigned msg,
756 DWORD_PTR user, DWORD_PTR unused1,
759 struct vlc_timer *timer = (struct vlc_timer *) user;
760 assert (timer_id == timer->id);
765 timer->func (timer->data);
769 mtime_t interval = timer->interval * 1000;
770 vlc_timer_schedule (timer, false, interval, interval);
775 int vlc_timer_create (vlc_timer_t *id, void (*func) (void *), void *data)
777 struct vlc_timer *timer = malloc (sizeof (*timer));
784 timer->handle = INVALID_HANDLE_VALUE;
793 void vlc_timer_destroy (vlc_timer_t timer)
796 if (timer->handle != INVALID_HANDLE_VALUE)
797 DeleteTimerQueueTimer (NULL, timer->handle, INVALID_HANDLE_VALUE);
800 timeKillEvent (timer->id);
801 /* FIXME: timers that have not yet completed will trigger use-after-free */
806 void vlc_timer_schedule (vlc_timer_t timer, bool absolute,
807 mtime_t value, mtime_t interval)
810 if (timer->handle != INVALID_HANDLE_VALUE)
812 DeleteTimerQueueTimer (NULL, timer->handle, NULL);
813 timer->handle = INVALID_HANDLE_VALUE;
818 timeKillEvent (timer->id);
828 value = (value + 999) / 1000;
829 interval = (interval + 999) / 1000;
832 if (!CreateTimerQueueTimer (&timer->handle, NULL, vlc_timer_do, timer,
833 value, interval, WT_EXECUTEDEFAULT))
836 timeGetDevCaps (&caps, sizeof(caps));
838 unsigned delay = value;
839 delay = __MAX(delay, caps.wPeriodMin);
840 delay = __MIN(delay, caps.wPeriodMax);
842 unsigned event = TIME_ONESHOT;
844 if (interval == delay)
845 event = TIME_PERIODIC;
847 timer->interval = interval;
849 timer->id = timeSetEvent (delay, delay / 20, vlc_timer_do, (DWORD) timer,
856 unsigned vlc_timer_getoverrun (vlc_timer_t timer)