| OLD | NEW |
| (Empty) |
| 1 #ifndef SkLazyFnPtr_DEFINED | |
| 2 #define SkLazyFnPtr_DEFINED | |
| 3 | |
| 4 /** Declare a lazily-chosen static function pointer of type F. | |
| 5 * | |
| 6 * Example usage: | |
| 7 * | |
| 8 * typedef int (*FooImpl)(int, int); | |
| 9 * | |
| 10 * static FooImpl choose_foo() { return ... }; | |
| 11 * | |
| 12 * int Foo(int a, int b) { | |
| 13 * SK_DECLARE_STATIC_LAZY_FN_PTR(FooImpl, choice); | |
| 14 * return choice.get(choose_foo)(a, b); | |
| 15 * } | |
| 16 * | |
| 17 * You can think of SK_DECLARE_STATIC_LAZY_FN_PTR as a cheaper specialization o
f SkOnce. | |
| 18 * There is no mutex, and in the fast path, no memory barriers are issued. | |
| 19 * | |
| 20 * This must be used in a global or function scope, not as a class member. | |
| 21 */ | |
| 22 #define SK_DECLARE_STATIC_LAZY_FN_PTR(F, name) static Private::SkLazyFnPtr<F> na
me = { NULL } | |
| 23 | |
| 24 | |
| 25 // Everything below here is private implementation details. Don't touch, don't
even look. | |
| 26 | |
| 27 #include "SkDynamicAnnotations.h" | |
| 28 #include "SkThread.h" | |
| 29 | |
| 30 namespace Private { | |
| 31 | |
| 32 // This has no constructor and is link-time initialized, so its members must be
public. | |
| 33 template <typename F> | |
| 34 struct SkLazyFnPtr { | |
| 35 F get(F (*choose)()) { | |
| 36 // First, try reading to see if it's already set. | |
| 37 F fn = (F)SK_ANNOTATE_UNPROTECTED_READ(fPtr); | |
| 38 if (fn != NULL) { | |
| 39 return fn; | |
| 40 } | |
| 41 | |
| 42 // We think it's not already set. | |
| 43 fn = choose(); | |
| 44 | |
| 45 // No particular memory barriers needed; we're not guarding anything but
the pointer itself. | |
| 46 F prev = (F)sk_atomic_cas(&fPtr, NULL, (void*)fn); | |
| 47 | |
| 48 // If prev != NULL, someone snuck in and set fPtr concurrently. | |
| 49 // If prev == NULL, we did write fn to fPtr. | |
| 50 return prev != NULL ? prev : fn; | |
| 51 } | |
| 52 | |
| 53 void* fPtr; | |
| 54 }; | |
| 55 | |
| 56 } // namespace Private | |
| 57 | |
| 58 #endif//SkLazyFnPtr_DEFINED | |
| OLD | NEW |