]> git.sesse.net Git - ffmpeg/blob - compat/w32pthreads.h
Merge commit '11c5f438ff83da5040e85bfa6299f56b321d32ef'
[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     thread->handle = (void*)_beginthreadex(NULL, 0, win32thread_worker, thread,
86                                            0, NULL);
87     return !thread->handle;
88 }
89
90 static av_unused int pthread_join(pthread_t thread, void **value_ptr)
91 {
92     DWORD ret = WaitForSingleObject(thread.handle, INFINITE);
93     if (ret != WAIT_OBJECT_0) {
94         if (ret == WAIT_ABANDONED)
95             return EINVAL;
96         else
97             return EDEADLK;
98     }
99     if (value_ptr)
100         *value_ptr = thread.ret;
101     CloseHandle(thread.handle);
102     return 0;
103 }
104
105 static inline int pthread_mutex_init(pthread_mutex_t *m, void* attr)
106 {
107     InitializeCriticalSection(m);
108     return 0;
109 }
110 static inline int pthread_mutex_destroy(pthread_mutex_t *m)
111 {
112     DeleteCriticalSection(m);
113     return 0;
114 }
115 static inline int pthread_mutex_lock(pthread_mutex_t *m)
116 {
117     EnterCriticalSection(m);
118     return 0;
119 }
120 static inline int pthread_mutex_unlock(pthread_mutex_t *m)
121 {
122     LeaveCriticalSection(m);
123     return 0;
124 }
125
126 #if _WIN32_WINNT >= 0x0600
127 typedef INIT_ONCE pthread_once_t;
128 #define PTHREAD_ONCE_INIT INIT_ONCE_STATIC_INIT
129
130 static av_unused int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
131 {
132     BOOL pending = FALSE;
133     InitOnceBeginInitialize(once_control, 0, &pending, NULL);
134     if (pending)
135         init_routine();
136     InitOnceComplete(once_control, 0, NULL);
137     return 0;
138 }
139
140 static inline int pthread_cond_init(pthread_cond_t *cond, const void *unused_attr)
141 {
142     InitializeConditionVariable(cond);
143     return 0;
144 }
145
146 /* native condition variables do not destroy */
147 static inline int pthread_cond_destroy(pthread_cond_t *cond)
148 {
149     return 0;
150 }
151
152 static inline int pthread_cond_broadcast(pthread_cond_t *cond)
153 {
154     WakeAllConditionVariable(cond);
155     return 0;
156 }
157
158 static inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
159 {
160     SleepConditionVariableCS(cond, mutex, INFINITE);
161     return 0;
162 }
163
164 static inline int pthread_cond_signal(pthread_cond_t *cond)
165 {
166     WakeConditionVariable(cond);
167     return 0;
168 }
169
170 #else // _WIN32_WINNT < 0x0600
171
172 /* atomic init state of dynamically loaded functions */
173 static LONG w32thread_init_state = 0;
174 static av_unused void w32thread_init(void);
175
176 /* for pre-Windows 6.0 platforms, define INIT_ONCE struct,
177  * compatible to the one used in the native API */
178
179 typedef union pthread_once_t  {
180     void * Ptr;    ///< For the Windows 6.0+ native functions
181     LONG state;    ///< For the pre-Windows 6.0 compat code
182 } pthread_once_t;
183
184 #define PTHREAD_ONCE_INIT {0}
185
186 /* function pointers to init once API on windows 6.0+ kernels */
187 static BOOL (WINAPI *initonce_begin)(pthread_once_t *lpInitOnce, DWORD dwFlags, BOOL *fPending, void **lpContext);
188 static BOOL (WINAPI *initonce_complete)(pthread_once_t *lpInitOnce, DWORD dwFlags, void *lpContext);
189
190 /* pre-Windows 6.0 compat using a spin-lock */
191 static inline void w32thread_once_fallback(LONG volatile *state, void (*init_routine)(void))
192 {
193     switch (InterlockedCompareExchange(state, 1, 0)) {
194     /* Initial run */
195     case 0:
196         init_routine();
197         InterlockedExchange(state, 2);
198         break;
199     /* Another thread is running init */
200     case 1:
201         while (1) {
202             MemoryBarrier();
203             if (*state == 2)
204                 break;
205             Sleep(0);
206         }
207         break;
208     /* Initialization complete */
209     case 2:
210         break;
211     }
212 }
213
214 static av_unused int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
215 {
216     w32thread_once_fallback(&w32thread_init_state, w32thread_init);
217
218     /* Use native functions on Windows 6.0+ */
219     if (initonce_begin && initonce_complete) {
220         BOOL pending = FALSE;
221         initonce_begin(once_control, 0, &pending, NULL);
222         if (pending)
223             init_routine();
224         initonce_complete(once_control, 0, NULL);
225         return 0;
226     }
227
228     w32thread_once_fallback(&once_control->state, init_routine);
229     return 0;
230 }
231
232 /* for pre-Windows 6.0 platforms we need to define and use our own condition
233  * variable and api */
234
235 typedef struct  win32_cond_t {
236     pthread_mutex_t mtx_broadcast;
237     pthread_mutex_t mtx_waiter_count;
238     volatile int waiter_count;
239     HANDLE semaphore;
240     HANDLE waiters_done;
241     volatile int is_broadcast;
242 } win32_cond_t;
243
244 /* function pointers to conditional variable API on windows 6.0+ kernels */
245 static void (WINAPI *cond_broadcast)(pthread_cond_t *cond);
246 static void (WINAPI *cond_init)(pthread_cond_t *cond);
247 static void (WINAPI *cond_signal)(pthread_cond_t *cond);
248 static BOOL (WINAPI *cond_wait)(pthread_cond_t *cond, pthread_mutex_t *mutex,
249                                 DWORD milliseconds);
250
251 static av_unused int pthread_cond_init(pthread_cond_t *cond, const void *unused_attr)
252 {
253     win32_cond_t *win32_cond = NULL;
254
255     w32thread_once_fallback(&w32thread_init_state, w32thread_init);
256
257     if (cond_init) {
258         cond_init(cond);
259         return 0;
260     }
261
262     /* non native condition variables */
263     win32_cond = av_mallocz(sizeof(win32_cond_t));
264     if (!win32_cond)
265         return ENOMEM;
266     cond->Ptr = win32_cond;
267     win32_cond->semaphore = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
268     if (!win32_cond->semaphore)
269         return ENOMEM;
270     win32_cond->waiters_done = CreateEvent(NULL, TRUE, FALSE, NULL);
271     if (!win32_cond->waiters_done)
272         return ENOMEM;
273
274     pthread_mutex_init(&win32_cond->mtx_waiter_count, NULL);
275     pthread_mutex_init(&win32_cond->mtx_broadcast, NULL);
276     return 0;
277 }
278
279 static av_unused int pthread_cond_destroy(pthread_cond_t *cond)
280 {
281     win32_cond_t *win32_cond = cond->Ptr;
282     /* native condition variables do not destroy */
283     if (cond_init)
284         return 0;
285
286     /* non native condition variables */
287     CloseHandle(win32_cond->semaphore);
288     CloseHandle(win32_cond->waiters_done);
289     pthread_mutex_destroy(&win32_cond->mtx_waiter_count);
290     pthread_mutex_destroy(&win32_cond->mtx_broadcast);
291     av_freep(&win32_cond);
292     cond->Ptr = NULL;
293     return 0;
294 }
295
296 static av_unused int pthread_cond_broadcast(pthread_cond_t *cond)
297 {
298     win32_cond_t *win32_cond = cond->Ptr;
299     int have_waiter;
300
301     if (cond_broadcast) {
302         cond_broadcast(cond);
303         return 0;
304     }
305
306     /* non native condition variables */
307     pthread_mutex_lock(&win32_cond->mtx_broadcast);
308     pthread_mutex_lock(&win32_cond->mtx_waiter_count);
309     have_waiter = 0;
310
311     if (win32_cond->waiter_count) {
312         win32_cond->is_broadcast = 1;
313         have_waiter = 1;
314     }
315
316     if (have_waiter) {
317         ReleaseSemaphore(win32_cond->semaphore, win32_cond->waiter_count, NULL);
318         pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
319         WaitForSingleObject(win32_cond->waiters_done, INFINITE);
320         ResetEvent(win32_cond->waiters_done);
321         win32_cond->is_broadcast = 0;
322     } else
323         pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
324     pthread_mutex_unlock(&win32_cond->mtx_broadcast);
325     return 0;
326 }
327
328 static av_unused int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
329 {
330     win32_cond_t *win32_cond = cond->Ptr;
331     int last_waiter;
332     if (cond_wait) {
333         cond_wait(cond, mutex, INFINITE);
334         return 0;
335     }
336
337     /* non native condition variables */
338     pthread_mutex_lock(&win32_cond->mtx_broadcast);
339     pthread_mutex_lock(&win32_cond->mtx_waiter_count);
340     win32_cond->waiter_count++;
341     pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
342     pthread_mutex_unlock(&win32_cond->mtx_broadcast);
343
344     // unlock the external mutex
345     pthread_mutex_unlock(mutex);
346     WaitForSingleObject(win32_cond->semaphore, INFINITE);
347
348     pthread_mutex_lock(&win32_cond->mtx_waiter_count);
349     win32_cond->waiter_count--;
350     last_waiter = !win32_cond->waiter_count || !win32_cond->is_broadcast;
351     pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
352
353     if (last_waiter)
354         SetEvent(win32_cond->waiters_done);
355
356     // lock the external mutex
357     return pthread_mutex_lock(mutex);
358 }
359
360 static av_unused int pthread_cond_signal(pthread_cond_t *cond)
361 {
362     win32_cond_t *win32_cond = cond->Ptr;
363     int have_waiter;
364     if (cond_signal) {
365         cond_signal(cond);
366         return 0;
367     }
368
369     pthread_mutex_lock(&win32_cond->mtx_broadcast);
370
371     /* non-native condition variables */
372     pthread_mutex_lock(&win32_cond->mtx_waiter_count);
373     have_waiter = win32_cond->waiter_count;
374     pthread_mutex_unlock(&win32_cond->mtx_waiter_count);
375
376     if (have_waiter) {
377         ReleaseSemaphore(win32_cond->semaphore, 1, NULL);
378         WaitForSingleObject(win32_cond->waiters_done, INFINITE);
379         ResetEvent(win32_cond->waiters_done);
380     }
381
382     pthread_mutex_unlock(&win32_cond->mtx_broadcast);
383     return 0;
384 }
385 #endif
386
387 static av_unused void w32thread_init(void)
388 {
389 #if _WIN32_WINNT < 0x0600
390     HANDLE kernel_dll = GetModuleHandle(TEXT("kernel32.dll"));
391     /* if one is available, then they should all be available */
392     cond_init      =
393         (void*)GetProcAddress(kernel_dll, "InitializeConditionVariable");
394     cond_broadcast =
395         (void*)GetProcAddress(kernel_dll, "WakeAllConditionVariable");
396     cond_signal    =
397         (void*)GetProcAddress(kernel_dll, "WakeConditionVariable");
398     cond_wait      =
399         (void*)GetProcAddress(kernel_dll, "SleepConditionVariableCS");
400     initonce_begin =
401         (void*)GetProcAddress(kernel_dll, "InitOnceBeginInitialize");
402     initonce_complete =
403         (void*)GetProcAddress(kernel_dll, "InitOnceComplete");
404 #endif
405
406 }
407
408 #endif /* FFMPEG_COMPAT_W32PTHREADS_H */