2 * Copyright (c) 2011 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
11 #ifndef VPX_PORTS_VPX_ONCE_H_
12 #define VPX_PORTS_VPX_ONCE_H_
14 #include "vpx_config.h"
16 #if CONFIG_MULTITHREAD && defined(_WIN32)
19 static void once(void (*func)(void))
21 static CRITICAL_SECTION *lock;
24 void *lock_ptr = &lock;
26 /* If the initialization is complete, return early. This isn't just an
27 * optimization, it prevents races on the destruction of the global
33 InterlockedIncrement(&waiters);
35 /* Get a lock. We create one and try to make it the one-true-lock,
36 * throwing it away if we lost the race.
40 /* Scope to protect access to new_lock */
41 CRITICAL_SECTION *new_lock = malloc(sizeof(CRITICAL_SECTION));
42 InitializeCriticalSection(new_lock);
43 if (InterlockedCompareExchangePointer(lock_ptr, new_lock, NULL) != NULL)
45 DeleteCriticalSection(new_lock);
50 /* At this point, we have a lock that can be synchronized on. We don't
51 * care which thread actually performed the allocation.
54 EnterCriticalSection(lock);
62 LeaveCriticalSection(lock);
64 /* Last one out should free resources. The destructed objects are
65 * protected by checking if(done) above.
67 if(!InterlockedDecrement(&waiters))
69 DeleteCriticalSection(lock);
76 #elif CONFIG_MULTITHREAD && defined(__OS2__)
79 static void once(void (*func)(void))
83 /* If the initialization is complete, return early. */
87 /* Causes all other threads in the process to block themselves
88 * and give up their time slice.
98 /* Restores normal thread dispatching for the current process. */
103 #elif CONFIG_MULTITHREAD && HAVE_PTHREAD_H
105 static void once(void (*func)(void))
107 static pthread_once_t lock = PTHREAD_ONCE_INIT;
108 pthread_once(&lock, func);
113 /* No-op version that performs no synchronization. vp8_rtcd() is idempotent,
114 * so as long as your platform provides atomic loads/stores of pointers
115 * no synchronization is strictly necessary.
118 static void once(void (*func)(void))
130 #endif // VPX_PORTS_VPX_ONCE_H_