1 // Copyright (C) 2014 The Android Open Source Project
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 #include "emugl/common/lazy_instance.h"
18 # define WIN32_LEAN_AND_MEAN 1
27 typedef LazyInstanceState::AtomicType AtomicType;
30 static inline void compilerBarrier() {
31 __asm__ __volatile__ ("" : : : "memory");
34 #error "Your compiler is not supported"
37 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
38 # define acquireBarrier() compilerBarrier()
39 # define releaseBarrier() compilerBarrier()
41 # error "Your CPU is not supported"
44 static inline AtomicType loadAcquire(AtomicType volatile* ptr) {
45 AtomicType ret = *ptr;
50 static inline void storeRelease(AtomicType volatile* ptr, AtomicType value) {
55 static int atomicCompareAndSwap(AtomicType volatile* ptr,
59 return InterlockedCompareExchange(ptr, value, expected);
60 #elif defined(__GNUC__)
61 return __sync_val_compare_and_swap(ptr, expected, value);
63 #error "Your compiler is not supported"
67 static void yieldThread() {
75 bool LazyInstanceState::inInitState() {
76 return loadAcquire(&mState) == STATE_INIT;
79 bool LazyInstanceState::needConstruction() {
80 AtomicType state = loadAcquire(&mState);
81 if (mState == STATE_DONE)
84 state = atomicCompareAndSwap(&mState, STATE_INIT, STATE_CONSTRUCTING);
85 if (state == STATE_INIT)
90 state = loadAcquire(&mState);
91 } while (state != STATE_DONE);
96 void LazyInstanceState::doneConstructing() {
97 storeRelease(&mState, STATE_DONE);
100 } // namespace internal