OLD | NEW |
(Empty) | |
| 1 /* |
| 2 * Copyright 2015 Google Inc. |
| 3 * |
| 4 * Use of this source code is governed by a BSD-style license that can be |
| 5 * found in the LICENSE file. |
| 6 */ |
| 7 |
| 8 #ifndef SkOncePtr_DEFINED |
| 9 #define SkOncePtr_DEFINED |
| 10 |
| 11 #include "../private/SkAtomics.h" |
| 12 #include <memory> |
| 13 |
| 14 // Use this to create a global static pointer that's intialized exactly once whe
n you call get(). |
| 15 #define SK_DECLARE_STATIC_ONCE_PTR(type, name) namespace {} static SkBaseOncePtr
<type> name; |
| 16 |
| 17 template <typename T> |
| 18 class SkBaseOncePtr { |
| 19 public: |
| 20 template <typename F> |
| 21 T* get(const F& f) const { |
| 22 uintptr_t state = sk_atomic_load(&fState, sk_memory_order_acquire); |
| 23 if (state < 2) { |
| 24 if (state == 0) { |
| 25 // It looks like no one has tried to create our pointer yet. |
| 26 // We try to claim that task by atomically swapping our state fr
om '0' to '1'. |
| 27 // See SkOnce.h for why we use an acquire memory order here rath
er than relaxed. |
| 28 if (sk_atomic_compare_exchange( |
| 29 &fState, &state, (uintptr_t)1, sk_memory_order_acquire, sk_m
emory_order_acquire)) { |
| 30 // We've claimed it. Create our pointer and store it into f
State. |
| 31 state = (uintptr_t)f(); |
| 32 SkASSERT(state > 1); |
| 33 sk_atomic_store(&fState, state, sk_memory_order_release); |
| 34 } else { |
| 35 // Someone else claimed it. |
| 36 // We fall through to the spin loop just below to wait for t
hem to finish. |
| 37 } |
| 38 } |
| 39 |
| 40 while (state == 1) { |
| 41 // State '1' is our busy-but-not-done state. |
| 42 // Some other thread has claimed the job of creating our pointer
. |
| 43 // We just need to wait for it to finish. |
| 44 state = sk_atomic_load(&fState, sk_memory_order_acquire); |
| 45 } |
| 46 |
| 47 // We shouldn't be able to get here without having created our point
er. |
| 48 SkASSERT(state > 1); |
| 49 } |
| 50 return (T*)state; |
| 51 } |
| 52 |
| 53 operator T*() const { |
| 54 auto state = sk_atomic_load(&fState, sk_memory_order_acquire); |
| 55 return state < 2 ? nullptr : (T*)state; |
| 56 // TODO: If state == 1 spin until it's not? |
| 57 } |
| 58 |
| 59 // fState == 0 --> we have not created our ptr yet |
| 60 // fState == 1 --> someone is in the middle of creating our ptr |
| 61 // else --> (T*)fState is our ptr |
| 62 mutable uintptr_t fState; |
| 63 }; |
| 64 |
| 65 #endif//SkOncePtr_DEFINED |
OLD | NEW |