1 /*
2  * Copyright (c) 2016, Alliance for Open Media. All rights reserved
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10  */
11 //
12 // Multi-threaded worker
13 //
14 // Original source:
15 //  https://chromium.googlesource.com/webm/libwebp
16 
17 #ifndef AOM_AOM_UTIL_AOM_THREAD_H_
18 #define AOM_AOM_UTIL_AOM_THREAD_H_
19 
20 #include "config/aom_config.h"
21 
22 #ifdef __cplusplus
23 extern "C" {
24 #endif
25 
26 #define MAX_NUM_THREADS 64
27 
28 #if CONFIG_MULTITHREAD
29 
30 #if defined(_WIN32) && !HAVE_PTHREAD_H
31 #include <errno.h>    // NOLINT
32 #include <process.h>  // NOLINT
33 #include <windows.h>  // NOLINT
34 typedef HANDLE pthread_t;
35 typedef CRITICAL_SECTION pthread_mutex_t;
36 
37 #if _WIN32_WINNT < 0x0600
38 #error _WIN32_WINNT must target Windows Vista / Server 2008 or newer.
39 #endif
40 typedef CONDITION_VARIABLE pthread_cond_t;
41 
42 #ifndef WINAPI_FAMILY_PARTITION
43 #define WINAPI_PARTITION_DESKTOP 1
44 #define WINAPI_FAMILY_PARTITION(x) x
45 #endif
46 
47 #if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
48 #define USE_CREATE_THREAD
49 #endif
50 
51 //------------------------------------------------------------------------------
52 // simplistic pthread emulation layer
53 
54 // _beginthreadex requires __stdcall
55 #define THREADFN unsigned int __stdcall
56 #define THREAD_RETURN(val) (unsigned int)((DWORD_PTR)val)
57 
pthread_create(pthread_t * const thread,const void * attr,unsigned int (__stdcall * start)(void *),void * arg)58 static INLINE int pthread_create(pthread_t *const thread, const void *attr,
59                                  unsigned int(__stdcall *start)(void *),
60                                  void *arg) {
61   (void)attr;
62 #ifdef USE_CREATE_THREAD
63   *thread = CreateThread(NULL,          /* lpThreadAttributes */
64                          0,             /* dwStackSize */
65                          start, arg, 0, /* dwStackSize */
66                          NULL);         /* lpThreadId */
67 #else
68   *thread = (pthread_t)_beginthreadex(NULL,          /* void *security */
69                                       0,             /* unsigned stack_size */
70                                       start, arg, 0, /* unsigned initflag */
71                                       NULL);         /* unsigned *thrdaddr */
72 #endif
73   if (*thread == NULL) return 1;
74   SetThreadPriority(*thread, THREAD_PRIORITY_ABOVE_NORMAL);
75   return 0;
76 }
77 
pthread_join(pthread_t thread,void ** value_ptr)78 static INLINE int pthread_join(pthread_t thread, void **value_ptr) {
79   (void)value_ptr;
80   return (WaitForSingleObjectEx(thread, INFINITE, FALSE /*bAlertable*/) !=
81               WAIT_OBJECT_0 ||
82           CloseHandle(thread) == 0);
83 }
84 
85 // Mutex
pthread_mutex_init(pthread_mutex_t * const mutex,void * mutexattr)86 static INLINE int pthread_mutex_init(pthread_mutex_t *const mutex,
87                                      void *mutexattr) {
88   (void)mutexattr;
89   InitializeCriticalSectionEx(mutex, 0 /*dwSpinCount*/, 0 /*Flags*/);
90   return 0;
91 }
92 
pthread_mutex_trylock(pthread_mutex_t * const mutex)93 static INLINE int pthread_mutex_trylock(pthread_mutex_t *const mutex) {
94   return TryEnterCriticalSection(mutex) ? 0 : EBUSY;
95 }
96 
pthread_mutex_lock(pthread_mutex_t * const mutex)97 static INLINE int pthread_mutex_lock(pthread_mutex_t *const mutex) {
98   EnterCriticalSection(mutex);
99   return 0;
100 }
101 
pthread_mutex_unlock(pthread_mutex_t * const mutex)102 static INLINE int pthread_mutex_unlock(pthread_mutex_t *const mutex) {
103   LeaveCriticalSection(mutex);
104   return 0;
105 }
106 
pthread_mutex_destroy(pthread_mutex_t * const mutex)107 static INLINE int pthread_mutex_destroy(pthread_mutex_t *const mutex) {
108   DeleteCriticalSection(mutex);
109   return 0;
110 }
111 
112 // Condition
pthread_cond_destroy(pthread_cond_t * const condition)113 static INLINE int pthread_cond_destroy(pthread_cond_t *const condition) {
114   (void)condition;
115   return 0;
116 }
117 
pthread_cond_init(pthread_cond_t * const condition,void * cond_attr)118 static INLINE int pthread_cond_init(pthread_cond_t *const condition,
119                                     void *cond_attr) {
120   (void)cond_attr;
121   InitializeConditionVariable(condition);
122   return 0;
123 }
124 
pthread_cond_signal(pthread_cond_t * const condition)125 static INLINE int pthread_cond_signal(pthread_cond_t *const condition) {
126   WakeConditionVariable(condition);
127   return 0;
128 }
129 
pthread_cond_broadcast(pthread_cond_t * const condition)130 static INLINE int pthread_cond_broadcast(pthread_cond_t *const condition) {
131   WakeAllConditionVariable(condition);
132   return 0;
133 }
134 
pthread_cond_wait(pthread_cond_t * const condition,pthread_mutex_t * const mutex)135 static INLINE int pthread_cond_wait(pthread_cond_t *const condition,
136                                     pthread_mutex_t *const mutex) {
137   int ok;
138   ok = SleepConditionVariableCS(condition, mutex, INFINITE);
139   return !ok;
140 }
141 #elif defined(__OS2__)
142 #define INCL_DOS
143 #include <os2.h>  // NOLINT
144 
145 #include <errno.h>        // NOLINT
146 #include <stdlib.h>       // NOLINT
147 #include <sys/builtin.h>  // NOLINT
148 
149 #define pthread_t TID
150 #define pthread_mutex_t HMTX
151 
152 typedef struct {
153   HEV event_sem_;
154   HEV ack_sem_;
155   volatile unsigned wait_count_;
156 } pthread_cond_t;
157 
158 //------------------------------------------------------------------------------
159 // simplistic pthread emulation layer
160 
161 #define THREADFN void *
162 #define THREAD_RETURN(val) (val)
163 
164 typedef struct {
165   void *(*start_)(void *);
166   void *arg_;
167 } thread_arg;
168 
169 static void thread_start(void *arg) {
170   thread_arg targ = *(thread_arg *)arg;
171   free(arg);
172 
173   targ.start_(targ.arg_);
174 }
175 
176 static INLINE int pthread_create(pthread_t *const thread, const void *attr,
177                                  void *(*start)(void *), void *arg) {
178   int tid;
179   thread_arg *targ = (thread_arg *)malloc(sizeof(*targ));
180   if (targ == NULL) return 1;
181 
182   (void)attr;
183 
184   targ->start_ = start;
185   targ->arg_ = arg;
186   tid = (pthread_t)_beginthread(thread_start, NULL, 1024 * 1024, targ);
187   if (tid == -1) {
188     free(targ);
189     return 1;
190   }
191 
192   *thread = tid;
193   return 0;
194 }
195 
196 static INLINE int pthread_join(pthread_t thread, void **value_ptr) {
197   (void)value_ptr;
198   return DosWaitThread(&thread, DCWW_WAIT) != 0;
199 }
200 
201 // Mutex
202 static INLINE int pthread_mutex_init(pthread_mutex_t *const mutex,
203                                      void *mutexattr) {
204   (void)mutexattr;
205   return DosCreateMutexSem(NULL, mutex, 0, FALSE) != 0;
206 }
207 
208 static INLINE int pthread_mutex_trylock(pthread_mutex_t *const mutex) {
209   return DosRequestMutexSem(*mutex, SEM_IMMEDIATE_RETURN) == 0 ? 0 : EBUSY;
210 }
211 
212 static INLINE int pthread_mutex_lock(pthread_mutex_t *const mutex) {
213   return DosRequestMutexSem(*mutex, SEM_INDEFINITE_WAIT) != 0;
214 }
215 
216 static INLINE int pthread_mutex_unlock(pthread_mutex_t *const mutex) {
217   return DosReleaseMutexSem(*mutex) != 0;
218 }
219 
220 static INLINE int pthread_mutex_destroy(pthread_mutex_t *const mutex) {
221   return DosCloseMutexSem(*mutex) != 0;
222 }
223 
224 // Condition
225 static INLINE int pthread_cond_destroy(pthread_cond_t *const condition) {
226   int ok = 1;
227   ok &= DosCloseEventSem(condition->event_sem_) == 0;
228   ok &= DosCloseEventSem(condition->ack_sem_) == 0;
229   return !ok;
230 }
231 
232 static INLINE int pthread_cond_init(pthread_cond_t *const condition,
233                                     void *cond_attr) {
234   int ok = 1;
235   (void)cond_attr;
236 
237   ok &=
238       DosCreateEventSem(NULL, &condition->event_sem_, DCE_POSTONE, FALSE) == 0;
239   ok &= DosCreateEventSem(NULL, &condition->ack_sem_, DCE_POSTONE, FALSE) == 0;
240   if (!ok) {
241     pthread_cond_destroy(condition);
242     return 1;
243   }
244   condition->wait_count_ = 0;
245   return 0;
246 }
247 
248 static INLINE int pthread_cond_signal(pthread_cond_t *const condition) {
249   int ok = 1;
250 
251   if (!__atomic_cmpxchg32(&condition->wait_count_, 0, 0)) {
252     ok &= DosPostEventSem(condition->event_sem_) == 0;
253     ok &= DosWaitEventSem(condition->ack_sem_, SEM_INDEFINITE_WAIT) == 0;
254   }
255 
256   return !ok;
257 }
258 
259 static INLINE int pthread_cond_broadcast(pthread_cond_t *const condition) {
260   int ok = 1;
261 
262   while (!__atomic_cmpxchg32(&condition->wait_count_, 0, 0))
263     ok &= pthread_cond_signal(condition) == 0;
264 
265   return !ok;
266 }
267 
268 static INLINE int pthread_cond_wait(pthread_cond_t *const condition,
269                                     pthread_mutex_t *const mutex) {
270   int ok = 1;
271 
272   __atomic_increment(&condition->wait_count_);
273 
274   ok &= pthread_mutex_unlock(mutex) == 0;
275 
276   ok &= DosWaitEventSem(condition->event_sem_, SEM_INDEFINITE_WAIT) == 0;
277 
278   __atomic_decrement(&condition->wait_count_);
279 
280   ok &= DosPostEventSem(condition->ack_sem_) == 0;
281 
282   pthread_mutex_lock(mutex);
283 
284   return !ok;
285 }
286 #else                 // _WIN32
287 #include <pthread.h>  // NOLINT
288 #define THREADFN void *
289 #define THREAD_RETURN(val) val
290 #endif
291 
292 #endif  // CONFIG_MULTITHREAD
293 
294 // State of the worker thread object
295 typedef enum {
296   NOT_OK = 0,  // object is unusable
297   OK,          // ready to work
298   WORK         // busy finishing the current task
299 } AVxWorkerStatus;
300 
301 // Function to be called by the worker thread. Takes two opaque pointers as
302 // arguments (data1 and data2). Should return true on success and return false
303 // in case of error.
304 typedef int (*AVxWorkerHook)(void *, void *);
305 
306 // Platform-dependent implementation details for the worker.
307 typedef struct AVxWorkerImpl AVxWorkerImpl;
308 
309 // Synchronization object used to launch job in the worker thread
310 typedef struct {
311   AVxWorkerImpl *impl_;
312   AVxWorkerStatus status_;
313   // Thread name for the debugger. If not NULL, must point to a string that
314   // outlives the worker thread. For portability, use a name <= 15 characters
315   // long (not including the terminating NUL character).
316   const char *thread_name;
317   AVxWorkerHook hook;  // hook to call
318   void *data1;         // first argument passed to 'hook'
319   void *data2;         // second argument passed to 'hook'
320   int had_error;       // true if a call to 'hook' returned false
321 } AVxWorker;
322 
323 // The interface for all thread-worker related functions. All these functions
324 // must be implemented.
325 typedef struct {
326   // Must be called first, before any other method.
327   void (*init)(AVxWorker *const worker);
328   // Must be called to initialize the object and spawn the thread. Re-entrant.
329   // Will potentially launch the thread. Returns false in case of error.
330   int (*reset)(AVxWorker *const worker);
331   // Makes sure the previous work is finished. Returns true if worker->had_error
332   // was not set and no error condition was triggered by the working thread.
333   int (*sync)(AVxWorker *const worker);
334   // Triggers the thread to call hook() with data1 and data2 arguments. These
335   // hook/data1/data2 values can be changed at any time before calling this
336   // function, but not be changed afterward until the next call to Sync().
337   void (*launch)(AVxWorker *const worker);
338   // This function is similar to launch() except that it calls the
339   // hook directly instead of using a thread. Convenient to bypass the thread
340   // mechanism while still using the AVxWorker structs. sync() must
341   // still be called afterward (for error reporting).
342   void (*execute)(AVxWorker *const worker);
343   // Kill the thread and terminate the object. To use the object again, one
344   // must call reset() again.
345   void (*end)(AVxWorker *const worker);
346 } AVxWorkerInterface;
347 
348 // Install a new set of threading functions, overriding the defaults. This
349 // should be done before any workers are started, i.e., before any encoding or
350 // decoding takes place. The contents of the interface struct are copied, it
351 // is safe to free the corresponding memory after this call. This function is
352 // not thread-safe. Return false in case of invalid pointer or methods.
353 int aom_set_worker_interface(const AVxWorkerInterface *const winterface);
354 
355 // Retrieve the currently set thread worker interface.
356 const AVxWorkerInterface *aom_get_worker_interface(void);
357 
358 //------------------------------------------------------------------------------
359 
360 #ifdef __cplusplus
361 }  // extern "C"
362 #endif
363 
364 #endif  // AOM_AOM_UTIL_AOM_THREAD_H_
365