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 assert (p_mutex != &super_mutex); /* this one cannot be static */
196 vlc_mutex_lock (&super_mutex);
197 while (p_mutex->locked)
199 p_mutex->contention++;
200 vlc_cond_wait (&super_variable, &super_mutex);
201 p_mutex->contention--;
203 p_mutex->locked = true;
204 vlc_mutex_unlock (&super_mutex);
208 EnterCriticalSection (&p_mutex->mutex);
211 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
213 if (!p_mutex->dynamic)
214 { /* static mutexes */
217 assert (p_mutex != &super_mutex); /* this one cannot be static */
218 vlc_mutex_lock (&super_mutex);
219 if (!p_mutex->locked)
221 p_mutex->locked = true;
224 vlc_mutex_unlock (&super_mutex);
228 return TryEnterCriticalSection (&p_mutex->mutex) ? 0 : EBUSY;
231 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
233 if (!p_mutex->dynamic)
234 { /* static mutexes */
235 assert (p_mutex != &super_mutex); /* this one cannot be static */
237 vlc_mutex_lock (&super_mutex);
238 assert (p_mutex->locked);
239 p_mutex->locked = false;
240 if (p_mutex->contention)
241 vlc_cond_broadcast (&super_variable);
242 vlc_mutex_unlock (&super_mutex);
246 LeaveCriticalSection (&p_mutex->mutex);
249 /*** Condition variables ***/
250 void vlc_cond_init( vlc_cond_t *p_condvar )
252 /* Create a manual-reset event (manual reset is needed for broadcast). */
253 *p_condvar = CreateEvent (NULL, TRUE, FALSE, NULL);
258 void vlc_cond_destroy (vlc_cond_t *p_condvar)
260 CloseHandle (*p_condvar);
263 void vlc_cond_signal (vlc_cond_t *p_condvar)
265 /* NOTE: This will cause a broadcast, that is wrong.
266 * This will also wake up the next waiting thread if no threads are yet
267 * waiting, which is also wrong. However both of these issues are allowed
268 * by the provision for spurious wakeups. Better have too many wakeups
269 * than too few (= deadlocks). */
270 SetEvent (*p_condvar);
273 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
275 SetEvent (*p_condvar);
278 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
282 assert (p_mutex->dynamic); /* TODO */
286 LeaveCriticalSection (&p_mutex->mutex);
287 result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
288 EnterCriticalSection (&p_mutex->mutex);
290 while (result == WAIT_IO_COMPLETION);
292 assert (result != WAIT_ABANDONED); /* another thread failed to cleanup! */
293 assert (result != WAIT_FAILED);
294 ResetEvent (*p_condvar);
297 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
302 assert (p_mutex->dynamic); /* TODO */
307 mtime_t total = (deadline - mdate ())/1000;
311 DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
312 LeaveCriticalSection (&p_mutex->mutex);
313 result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
314 EnterCriticalSection (&p_mutex->mutex);
316 while (result == WAIT_IO_COMPLETION);
318 assert (result != WAIT_ABANDONED);
319 assert (result != WAIT_FAILED);
320 ResetEvent (*p_condvar);
322 return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
326 void vlc_sem_init (vlc_sem_t *sem, unsigned value)
328 *sem = CreateSemaphore (NULL, value, 0x7fffffff, NULL);
333 void vlc_sem_destroy (vlc_sem_t *sem)
338 int vlc_sem_post (vlc_sem_t *sem)
340 ReleaseSemaphore (*sem, 1, NULL);
341 return 0; /* FIXME */
344 void vlc_sem_wait (vlc_sem_t *sem)
351 result = WaitForSingleObjectEx (*sem, INFINITE, TRUE);
353 while (result == WAIT_IO_COMPLETION);
356 /*** Read/write locks */
357 /* SRW (Slim Read Write) locks are available in Vista+ only */
358 void vlc_rwlock_init (vlc_rwlock_t *lock)
360 vlc_mutex_init (&lock->mutex);
361 vlc_cond_init (&lock->read_wait);
362 vlc_cond_init (&lock->write_wait);
363 lock->readers = 0; /* active readers */
364 lock->writers = 0; /* waiting or active writers */
365 lock->writer = 0; /* ID of active writer */
369 * Destroys an initialized unused read/write lock.
371 void vlc_rwlock_destroy (vlc_rwlock_t *lock)
373 vlc_cond_destroy (&lock->read_wait);
374 vlc_cond_destroy (&lock->write_wait);
375 vlc_mutex_destroy (&lock->mutex);
379 * Acquires a read/write lock for reading. Recursion is allowed.
381 void vlc_rwlock_rdlock (vlc_rwlock_t *lock)
383 vlc_mutex_lock (&lock->mutex);
384 while (lock->writer != 0)
385 vlc_cond_wait (&lock->read_wait, &lock->mutex);
386 if (lock->readers == ULONG_MAX)
389 vlc_mutex_unlock (&lock->mutex);
393 * Acquires a read/write lock for writing. Recursion is not allowed.
395 void vlc_rwlock_wrlock (vlc_rwlock_t *lock)
397 vlc_mutex_lock (&lock->mutex);
398 if (lock->writers == ULONG_MAX)
401 while ((lock->readers > 0) || (lock->writer != 0))
402 vlc_cond_wait (&lock->write_wait, &lock->mutex);
404 lock->writer = GetCurrentThreadId ();
405 vlc_mutex_unlock (&lock->mutex);
409 * Releases a read/write lock.
411 void vlc_rwlock_unlock (vlc_rwlock_t *lock)
413 vlc_mutex_lock (&lock->mutex);
414 if (lock->readers > 0)
415 lock->readers--; /* Read unlock */
417 lock->writer = 0; /* Write unlock */
419 if (lock->writers > 0)
421 if (lock->readers == 0)
422 vlc_cond_signal (&lock->write_wait);
425 vlc_cond_broadcast (&lock->read_wait);
426 vlc_mutex_unlock (&lock->mutex);
429 /*** Thread-specific variables (TLS) ***/
430 int vlc_threadvar_create (vlc_threadvar_t *p_tls, void (*destr) (void *))
432 #warning FIXME: use destr() callback and stop leaking!
436 return (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
439 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
445 * Sets a thread-local variable.
446 * @param key thread-local variable key (created with vlc_threadvar_create())
447 * @param value new value for the variable for the calling thread
448 * @return 0 on success, a system error code otherwise.
450 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
452 return TlsSetValue (key, value) ? ENOMEM : 0;
456 * Gets the value of a thread-local variable for the calling thread.
457 * This function cannot fail.
458 * @return the value associated with the given variable for the calling
459 * or NULL if there is no value.
461 void *vlc_threadvar_get (vlc_threadvar_t key)
463 return TlsGetValue (key);
468 void vlc_threads_setup (libvlc_int_t *p_libvlc)
473 struct vlc_entry_data
475 void * (*func) (void *);
482 static unsigned __stdcall vlc_entry (void *p)
484 vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
485 struct vlc_entry_data data;
487 memcpy (&data, p, sizeof (data));
491 cancel_data.cancel_event = data.cancel_event;
494 vlc_threadvar_set (cancel_key, &cancel_data);
495 data.func (data.data);
499 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
505 struct vlc_entry_data *entry_data = malloc (sizeof (*entry_data));
506 if (entry_data == NULL)
508 entry_data->func = entry;
509 entry_data->data = data;
512 /* When using the MSVCRT C library you have to use the _beginthreadex
513 * function instead of CreateThread, otherwise you'll end up with
514 * memory leaks and the signal functions not working (see Microsoft
515 * Knowledge Base, article 104641) */
516 hThread = (HANDLE)(uintptr_t)
517 _beginthreadex (NULL, 0, vlc_entry, entry_data, CREATE_SUSPENDED, NULL);
524 /* Thread closes the handle when exiting, duplicate it here
525 * to be on the safe side when joining. */
526 if (!DuplicateHandle (GetCurrentProcess (), hThread,
527 GetCurrentProcess (), p_handle, 0, FALSE,
528 DUPLICATE_SAME_ACCESS))
530 CloseHandle (hThread);
535 vlc_thread_t th = malloc (sizeof (*th));
538 th->cancel_event = CreateEvent (NULL, FALSE, FALSE, NULL);
539 if (th->cancel_event == NULL)
544 entry_data->cancel_event = th->cancel_event;
546 /* Not sure if CREATE_SUSPENDED + ResumeThread() is any useful on WinCE.
547 * Thread handles act up, too. */
548 th->handle = CreateThread (NULL, 128*1024, vlc_entry, entry_data,
549 CREATE_SUSPENDED, NULL);
550 if (th->handle == NULL)
552 CloseHandle (th->cancel_event);
558 hThread = th->handle;
562 ResumeThread (hThread);
564 SetThreadPriority (hThread, priority);
573 void vlc_join (vlc_thread_t handle, void **result)
576 # define handle handle->handle
580 while (WaitForSingleObjectEx (handle, INFINITE, TRUE)
581 == WAIT_IO_COMPLETION);
583 CloseHandle (handle);
584 assert (result == NULL); /* <- FIXME if ever needed */
587 CloseHandle (handle->cancel_event);
592 void vlc_detach (vlc_thread_t handle)
595 CloseHandle (handle);
597 /* FIXME: handle->cancel_event leak */
598 CloseHandle (handle->handle);
603 /*** Thread cancellation ***/
605 /* APC procedure for thread cancellation */
606 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
609 vlc_control_cancel (VLC_DO_CANCEL);
612 void vlc_cancel (vlc_thread_t thread_id)
615 QueueUserAPC (vlc_cancel_self, thread_id, 0);
617 SetEvent (thread_id->cancel_event);
621 int vlc_savecancel (void)
625 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
627 return false; /* Main thread - cannot be cancelled anyway */
629 state = nfo->killable;
630 nfo->killable = false;
634 void vlc_restorecancel (int state)
636 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
637 assert (state == false || state == true);
640 return; /* Main thread - cannot be cancelled anyway */
642 assert (!nfo->killable);
643 nfo->killable = state != 0;
646 void vlc_testcancel (void)
648 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
650 return; /* Main thread - cannot be cancelled anyway */
652 if (nfo->killable && nfo->killed)
654 for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
664 void vlc_control_cancel (int cmd, ...)
666 /* NOTE: This function only modifies thread-specific data, so there is no
667 * need to lock anything. */
670 vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
672 return; /* Main thread - cannot be cancelled anyway */
681 case VLC_CLEANUP_PUSH:
683 /* cleaner is a pointer to the caller stack, no need to allocate
684 * and copy anything. As a nice side effect, this cannot fail. */
685 vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
686 cleaner->next = nfo->cleaners;
687 nfo->cleaners = cleaner;
691 case VLC_CLEANUP_POP:
693 nfo->cleaners = nfo->cleaners->next;
710 void (*func) (void *);
715 static void CALLBACK vlc_timer_do (void *val, BOOLEAN timeout)
717 struct vlc_timer *timer = val;
720 timer->func (timer->data);
723 static void CALLBACK vlc_timer_do (unsigned timer_id, unsigned msg,
724 DWORD_PTR user, DWORD_PTR unused1,
727 struct vlc_timer *timer = (struct vlc_timer *) user;
728 assert (timer_id == timer->id);
733 timer->func (timer->data);
737 mtime_t interval = timer->interval * 1000;
738 vlc_timer_schedule (timer, false, interval, interval);
743 int vlc_timer_create (vlc_timer_t *id, void (*func) (void *), void *data)
745 struct vlc_timer *timer = malloc (sizeof (*timer));
752 timer->handle = INVALID_HANDLE_VALUE;
761 void vlc_timer_destroy (vlc_timer_t timer)
764 if (timer->handle != INVALID_HANDLE_VALUE)
765 DeleteTimerQueueTimer (NULL, timer->handle, INVALID_HANDLE_VALUE);
768 timeKillEvent (timer->id);
769 /* FIXME: timers that have not yet completed will trigger use-after-free */
774 void vlc_timer_schedule (vlc_timer_t timer, bool absolute,
775 mtime_t value, mtime_t interval)
778 if (timer->handle != INVALID_HANDLE_VALUE)
780 DeleteTimerQueueTimer (NULL, timer->handle, NULL);
781 timer->handle = INVALID_HANDLE_VALUE;
786 timeKillEvent (timer->id);
796 value = (value + 999) / 1000;
797 interval = (interval + 999) / 1000;
800 if (!CreateTimerQueueTimer (&timer->handle, NULL, vlc_timer_do, timer,
801 value, interval, WT_EXECUTEDEFAULT))
804 timeGetDevCaps (&caps, sizeof(caps));
806 unsigned delay = value;
807 delay = __MAX(delay, caps.wPeriodMin);
808 delay = __MIN(delay, caps.wPeriodMax);
810 unsigned event = TIME_ONESHOT;
812 if (interval == delay)
813 event = TIME_PERIODIC;
815 timer->interval = interval;
817 timer->id = timeSetEvent (delay, delay / 20, vlc_timer_do, (DWORD) timer,
824 unsigned vlc_timer_getoverrun (vlc_timer_t timer)