]> git.sesse.net Git - ffmpeg/blob - compat/w32pthreads.h
winrt: multithreading support
[ffmpeg] / compat / w32pthreads.h
1 /*
2  * Copyright (C) 2010-2011 x264 project
3  *
4  * Authors: Steven Walters <kemuri9@gmail.com>
5  *          Pegasys Inc. <http://www.pegasys-inc.com>
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 /**
25  * @file
26  * w32threads to pthreads wrapper
27  */
28
29 #ifndef FFMPEG_COMPAT_W32PTHREADS_H
30 #define FFMPEG_COMPAT_W32PTHREADS_H
31
32 /* Build up a pthread-like API using underlying Windows API. Have only static
33  * methods so as to not conflict with a potentially linked in pthread-win32
34  * library.
35  * As most functions here are used without checking return values,
36  * only implement return values as necessary. */
37
38 #define WIN32_LEAN_AND_MEAN
39 #include <windows.h>
40 #include <process.h>
41
42 #include "libavutil/attributes.h"
43 #include "libavutil/common.h"
44 #include "libavutil/internal.h"
45 #include "libavutil/mem.h"
46
47 typedef struct pthread_t {
48     void *handle;
49     void *(*func)(void* arg);
50     void *arg;
51     void *ret;
52 } pthread_t;
53
54 /* the conditional variable api for windows 6.0+ uses critical sections and
55  * not mutexes */
56 typedef CRITICAL_SECTION pthread_mutex_t;
57
58 /* This is the CONDITION_VARIABLE typedef for using Windows' native
59  * conditional variables on kernels 6.0+. */
60 #if HAVE_CONDITION_VARIABLE_PTR
61 typedef CONDITION_VARIABLE pthread_cond_t;
62 #else
63 typedef struct pthread_cond_t {
64     void *Ptr;
65 } pthread_cond_t;
66 #endif
67
68 #if _WIN32_WINNT >= 0x0600
69 #define InitializeCriticalSection(x) InitializeCriticalSectionEx(x, 0, 0)
70 #define WaitForSingleObject(a, b) WaitForSingleObjectEx(a, b, FALSE)
71 #endif
72
73 static av_unused unsigned __stdcall attribute_align_arg win32thread_worker(void *arg)
74 {
75     pthread_t *h = arg;
76     h->ret = h->func(h->arg);
77     return 0;
78 }
79
80 static av_unused int pthread_create(pthread_t *thread, const void *unused_attr,
81                                     void *(*start_routine)(void*), void *arg)
82 {
83     thread->func   = start_routine;
84     thread->arg    = arg;
85 #if HAVE_WINRT
86     thread->handle = (void*)CreateThread(NULL, 0, win32thread_worker, thread,
87                                            0, NULL);
88 #else
89     thread->handle = (void*)_beginthreadex(NULL, 0, win32thread_worker, thread,
90                                            0, NULL);
91 #endif
92     return !thread->handle;
93 }
94
95 static av_unused int pthread_join(pthread_t thread, void **value_ptr)
96 {
97     DWORD ret = WaitForSingleObject(thread.handle, INFINITE);
98     if (ret != WAIT_OBJECT_0) {
99         if (ret == WAIT_ABANDONED)
100             return EINVAL;
101         else
102             return EDEADLK;
103     }
104     if (value_ptr)
105         *value_ptr = thread.ret;
106     CloseHandle(thread.handle);
107     return 0;
108 }
109
110 static inline int pthread_mutex_init(pthread_mutex_t *m, void* attr)
111 {
112     InitializeCriticalSection(m);
113     return 0;
114 }
115 static inline int pthread_mutex_destroy(pthread_mutex_t *m)
116 {
117     DeleteCriticalSection(m);
118     return 0;
119 }
120 static inline int pthread_mutex_lock(pthread_mutex_t *m)
121 {
122     EnterCriticalSection(m);
123     return 0;
124 }
125 static inline int pthread_mutex_unlock(pthread_mutex_t *m)
126 {
127     LeaveCriticalSection(m);
128     return 0;
129 }
130
131 #if _WIN32_WINNT >= 0x0600
132 typedef INIT_ONCE pthread_once_t;
133 #define PTHREAD_ONCE_INIT INIT_ONCE_STATIC_INIT
134
135 static av_unused int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
136 {
137     BOOL pending = FALSE;
138     InitOnceBeginInitialize(once_control, 0, &pending, NULL);
139     if (pending)
140         init_routine();
141     InitOnceComplete(once_control, 0, NULL);
142     return 0;
143 }
144
145 static inline int pthread_cond_init(pthread_cond_t *cond, const void *unused_attr)
146 {
147     InitializeConditionVariable(cond);
148     return 0;
149 }
150
151 /* native condition variables do not destroy */
152 static inline int pthread_cond_destroy(pthread_cond_t *cond)
153 {
154     return 0;
155 }
156
157 static inline int pthread_cond_broadcast(pthread_cond_t *cond)
158 {
159     WakeAllConditionVariable(cond);
160     return 0;
161 }
162
163 static inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
164 {
165     SleepConditionVariableCS(cond, mutex, INFINITE);
166     return 0;
167 }
168
169 static inline int pthread_cond_signal(pthread_cond_t *cond)
170 {
171     WakeConditionVariable(cond);
172     return 0;
173 }
174
175 #else // _WIN32_WINNT < 0x0600
176
177 /* atomic init state of dynamically loaded functions */
178 static LONG w32thread_init_state = 0;
179 static av_unused void w32thread_init(void);
180
181 /* for pre-Windows 6.0 platforms, define INIT_ONCE struct,
182  * compatible to the one used in the native API */
183
184 typedef union pthread_once_t  {
185     void * Ptr;    ///< For the Windows 6.0+ native functions
186     LONG state;    ///< For the pre-Windows 6.0 compat code
187 } pthread_once_t;
188
189 #define PTHREAD_ONCE_INIT {0}
190
191 /* function pointers to init once API on windows 6.0+ kernels */
192 static BOOL (WINAPI *initonce_begin)(pthread_once_t *lpInitOnce, DWORD dwFlags, BOOL *fPending, void **lpContext);
193 static BOOL (WINAPI *initonce_complete)(pthread_once_t *lpInitOnce, DWORD dwFlags, void *lpContext);
194
195 /* pre-Windows 6.0 compat using a spin-lock */
196 static inline void w32thread_once_fallback(LONG volatile *state, void (*init_routine)(void))
197 {
198     switch (InterlockedCompareExchange(state, 1, 0)) {
199     /* Initial run */
200     case 0:
201         init_routine();
202         InterlockedExchange(state, 2);
203         break;
204     /* Another thread is running init */
205     case 1:
206         while (1) {
207             MemoryBarrier();
208             if (*state == 2)
209                 break;
210             Sleep(0);
211         }
212         break;
213     /* Initialization complete */
214     case 2:
215         break;
216     }
217 }
218
219 static av_unused int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
220 {
221     w32thread_once_fallback(&w32thread_init_state, w32thread_init);
222
223     /* Use native functions on Windows 6.0+ */
224     if (initonce_begin && initonce_complete) {
225         BOOL pending = FALSE;
226         initonce_begin(once_control, 0, &pending, NULL);
227         if (pending)
228             init_routine();
229         initonce_complete(once_control, 0, NULL);
230         return 0;
231     }
232
233     w32thread_once_fallback(&once_control->state, init_routine);
234     return 0;
235 }
236
237 /* for pre-Windows 6.0 platforms we need to define and use our own condition
238  * variable and api */
239
240 typedef struct  win32_cond_t {
241     pthread_mutex_t mtx_broadcast;
242     pthread_mutex_t mtx_waiter_count;
243     volatile int waiter_count;
244     HANDLE semaphore;
245     HANDLE waiters_done;
246     volatile int is_broadcast;
247 } win32_cond_t;
248
249 /* function pointers to conditional variable API on windows 6.0+ kernels */
250 static void (WINAPI *cond_broadcast)(pthread_cond_t *cond);
251 static void (WINAPI *cond_init)(pthread_cond_t *cond);
252 static void (WINAPI *cond_signal)(pthread_cond_t *cond);
253 static BOOL (WINAPI *cond_wait)(pthread_cond_t *cond, pthread_mutex_t *mutex,
254                                 DWORD milliseconds);
255
256 static av_unused int pthread_cond_init(pthread_cond_t *cond, const void *unused_attr)
257 {
258     win32_cond_t *win32_cond = NULL;
259
260     w32thread_once_fallback(&w32thread_init_state, w32thread_init);
261
262     if (cond_init) {
263         cond_init(cond);
264         return 0;
265     }
266
267     /* non native condition variables */
268     win32_cond = av_mallocz(sizeof(win32_cond_t));
269     if (!win32_cond)
270         return ENOMEM;
271     cond->Ptr = win32_cond;
272     win32_cond->semaphore = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
273     if (!win32_cond->semaphore)
274         return ENOMEM;
275     win32_cond->waiters_done = CreateEvent(NULL, TRUE, FALSE, NULL);
276     if (!win32_cond->waiters_done)
277         return ENOMEM;
278
279     pthread_mutex_init(&win32_cond->mtx_waiter_count, NULL);
280     pthread_mutex_init(&win32_cond->mtx_broadcast, NULL);
281     return 0;
282 }
283
284 static av_unused int pthread_cond_destroy(pthread_cond_t *cond)
285 {
286     win32_cond_t *win32_cond = cond->Ptr;
287     /* native condition variables do not destroy */
288     if (cond_init)
289         return 0;
290
291     /* non native condition variables */
292     CloseHandle(win32_cond->semaphore);
293     CloseHandle(win32_cond->waiters_done);
294     pthread_mutex_destroy(&win32_cond->mtx_waiter_count);
295     pthread_mutex_destroy(&win32_cond->mtx_broadcast);
296     av_freep(&win32_cond);
297     cond->Ptr = NULL;
298     return 0;
299 }
300
301 static av_unused int pthread_cond_broadcast(pthread_cond_t *cond)
302 {
303     win32_cond_t *win32_cond = cond->Ptr;
304     int have_waiter;
305
306     if (cond_broadcast) {
307         cond_broadcast(cond);
308         return 0;
309     }
310
311     /* non native condition variables */
312     pthread_mutex_lock(&win32_cond->mtx_broadcast);
313     pthread_mutex_lock(&win32_cond->mtx_waiter_count);
314     have_waiter = 0;
315
316     if (win32_cond->waiter_count) {
317         win32_cond->is_broadcast = 1;
318         have_waiter = 1;
319     }
320
321     if (have_waiter) {
322         ReleaseSemaphore(win32_cond->semaphore, win32_cond->waiter_count, NULL);
323         pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
324         WaitForSingleObject(win32_cond->waiters_done, INFINITE);
325         ResetEvent(win32_cond->waiters_done);
326         win32_cond->is_broadcast = 0;
327     } else
328         pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
329     pthread_mutex_unlock(&win32_cond->mtx_broadcast);
330     return 0;
331 }
332
333 static av_unused int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
334 {
335     win32_cond_t *win32_cond = cond->Ptr;
336     int last_waiter;
337     if (cond_wait) {
338         cond_wait(cond, mutex, INFINITE);
339         return 0;
340     }
341
342     /* non native condition variables */
343     pthread_mutex_lock(&win32_cond->mtx_broadcast);
344     pthread_mutex_lock(&win32_cond->mtx_waiter_count);
345     win32_cond->waiter_count++;
346     pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
347     pthread_mutex_unlock(&win32_cond->mtx_broadcast);
348
349     // unlock the external mutex
350     pthread_mutex_unlock(mutex);
351     WaitForSingleObject(win32_cond->semaphore, INFINITE);
352
353     pthread_mutex_lock(&win32_cond->mtx_waiter_count);
354     win32_cond->waiter_count--;
355     last_waiter = !win32_cond->waiter_count || !win32_cond->is_broadcast;
356     pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
357
358     if (last_waiter)
359         SetEvent(win32_cond->waiters_done);
360
361     // lock the external mutex
362     return pthread_mutex_lock(mutex);
363 }
364
365 static av_unused int pthread_cond_signal(pthread_cond_t *cond)
366 {
367     win32_cond_t *win32_cond = cond->Ptr;
368     int have_waiter;
369     if (cond_signal) {
370         cond_signal(cond);
371         return 0;
372     }
373
374     pthread_mutex_lock(&win32_cond->mtx_broadcast);
375
376     /* non-native condition variables */
377     pthread_mutex_lock(&win32_cond->mtx_waiter_count);
378     have_waiter = win32_cond->waiter_count;
379     pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
380
381     if (have_waiter) {
382         ReleaseSemaphore(win32_cond->semaphore, 1, NULL);
383         WaitForSingleObject(win32_cond->waiters_done, INFINITE);
384         ResetEvent(win32_cond->waiters_done);
385     }
386
387     pthread_mutex_unlock(&win32_cond->mtx_broadcast);
388     return 0;
389 }
390 #endif
391
392 static av_unused void w32thread_init(void)
393 {
394 #if _WIN32_WINNT < 0x0600
395     HANDLE kernel_dll = GetModuleHandle(TEXT("kernel32.dll"));
396     /* if one is available, then they should all be available */
397     cond_init      =
398         (void*)GetProcAddress(kernel_dll, "InitializeConditionVariable");
399     cond_broadcast =
400         (void*)GetProcAddress(kernel_dll, "WakeAllConditionVariable");
401     cond_signal    =
402         (void*)GetProcAddress(kernel_dll, "WakeConditionVariable");
403     cond_wait      =
404         (void*)GetProcAddress(kernel_dll, "SleepConditionVariableCS");
405     initonce_begin =
406         (void*)GetProcAddress(kernel_dll, "InitOnceBeginInitialize");
407     initonce_complete =
408         (void*)GetProcAddress(kernel_dll, "InitOnceComplete");
409 #endif
410
411 }
412
413 #endif /* FFMPEG_COMPAT_W32PTHREADS_H */